码迷,mamicode.com
首页 > 其他好文 > 详细

使用类目为UIColor类扩展一个类方法实现十六进制字符串转化成UIColor对象

时间:2015-05-04 23:33:39      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

#import <UIKit/UIKit.h>

 

@interface UIColor (ColorWithHexStrig)

+ (UIColor *)colorWithHexString:(NSString *)hexString;

@end

 

#import "UIColor+ColorWithHexStrig.h"

 

@implementation UIColor (ColorWithHexStrig)

//根据十六进制数值获取UIColor

+ (UIColor *)colorWithHexString:(NSString *)hexString{

    //去掉字符串两端的空格,并且取小写转换大写

    NSString *colorString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    //当给定的字符串长度小于6时,返回透明的

    if (colorString.length < 6) {

        return [UIColor clearColor];

    }

    // strip 0X if it appears

    if ([colorString hasPrefix:@"0X"])

        colorString = [colorString substringFromIndex:2];

    if ([colorString hasPrefix:@"#"])

        colorString = [colorString substringFromIndex:1];

    if ([colorString length] != 6)

        return [UIColor clearColor];

    

    unsigned int red = 0,green = 0,blue = 0;

    NSRange range = NSMakeRange(0, 2);

    [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&red];

    range.location = 2;

    [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&green];

    range.location = 4;

    [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&blue];

    return [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:1];

}

@end

 

使用类目为UIColor类扩展一个类方法实现十六进制字符串转化成UIColor对象

标签:

原文地址:http://www.cnblogs.com/wangguimin/p/4477913.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!