Use the class to extend a class method for the Uicolor class to implement a hexadecimal string into a Uicolor object

Source: Internet
Author: User

#import <UIKit/UIKit.h>

@interface Uicolor (Colorwithhexstrig)

+ (Uicolor *) colorwithhexstring: (NSString *) hexstring;

@end

#import "Uicolor+colorwithhexstrig.h"

@implementation Uicolor (Colorwithhexstrig)

Get uicolor based on hexadecimal values

+ (Uicolor *) colorwithhexstring: (NSString *) hexstring{

Remove the spaces at both ends of the string, and take lowercase conversions uppercase

NSString *colorstring = [[HexString stringbytrimmingcharactersinset:[nscharacterset Whitespaceandnewlinecharacterset]] uppercasestring];

When the given string length is less than 6 o'clock, returns the transparent

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

Use the class to extend a class method for the Uicolor class to implement a hexadecimal string into a Uicolor object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.