How can I create a UIColor from a hex string?

后端 未结 30 1558
北恋
北恋 2020-11-22 16:53

How can I create a UIColor from a hexadecimal string format, such as #00FF00?

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 17:12

    I ended up creating a category for UIColor that I can just reuse in my other projects, and added this function:

    + (UIColor *)colorFromHex:(unsigned long)hex
    {
        return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0
                               green:((float)((hex & 0xFF00) >> 8))/255.0
                                blue:((float)(hex & 0xFF))/255.0
                               alpha:1.0];
    }
    

    The usage goes like:

    UIColor *customRedColor = [UIColor colorFromHex:0x990000];
    

    This is far faster than passing on a string and converting it to a number then shifting the bits.

    You can also import the category from inside your .pch file so you can easily use colorFromHex everywhere in your app like it's built-in to UIColor:

    #ifdef __OBJC__
        #import 
        #import 
        // Your other stuff here...
        #import "UIColor+HexColor.h"
    #endif
    

提交回复
热议问题