How can I create a UIColor
from a hexadecimal string format, such as #00FF00
?
相关问题
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
- Get the NSRange for the visible text after scroll
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Xcode: Is there a way to change line spacing (UI L
- Swift - hide pickerView after value selected
- How do you detect key up / key down events from a
- didBeginContact:(SKPhysicsContact *)contact not in
A great Swift implementation (updated for Xcode 7) using extensions, pulled together from a variety of different answers and places. You will also need the string extensions at the end.
Use:
NOTE: I added an option for 2 additional digits to the end of the standard 6 digit hex value for an alpha channel (pass in value of
00
-99
). If this offends you, just remove it. You could implement it to pass in an optional alpha parameter.Extension:
String extensions:
Float source
Subscript source
Create elegant extension for
UIColor
:Create red color:
For swift 2.0+. This code works fine to me.
This code includes string format checking. e.g.
And as far as I know, my code is of no disadvantage for its maintaining the semantic of failible condition and returning an optional value. And this should be the best answer.
I've found the simplest way to do this is with a macro. Just include it in your header and it's available throughout your project.
uicolor macro with hex values
Also formatted version of this code:
Usage:
I've got a solution that is 100% compatible with the hex format strings used by Android, which I found very helpful when doing cross-platform mobile development. It lets me use one color palate for both platforms. Feel free to reuse without attribution, or under the Apache license if you prefer.
I found a good
UIColor
category for this, UIColor+PXExtensions.Usage:
UIColor *mycolor = [UIColor pxColorWithHexValue:@"#BADA55"];
And, just in case the link to my gist fails, here is the actual implementation code: