
Extension for UIColor Swift 5
Extensions are great..if you are an iOS Developer then you are already familiar with extensions, it is a great help and i love them a lot..
I have my own extensions which i had created in years and have been using them all from a long time.
After creating a new project or working on existing project, first thing i do is add my extensions file to the project, all of the extensions are so useful and i seriously use them a lot.
But one of my favourite is UIColor and if you prefer designing UI using Code then Colors extension is must.
We get gesign mockup from design team or get screenshots and have to extracts code codes, and there comes hex color codes, and this is where our extension comes. Most of the designers use hexadecimal codes and share the same in design files so i have an extension which i am going to share with you guys.
UIColor Extension for Hex Color Codes:-
extension UIColor {
convenience init(rgb: UInt) {
self.init(red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgb & 0x0000FF) / 255.0, alpha: CGFloat(1.0))
}
}
How to use it..??
Call the initializer and append 0x at the beginning of hex color code
view.backgroundColor = UIColor.init(rgb: 0xF58634)
For testing and creating views i generally use random colors which help me deisgn the UI more accurately and to replicate exact design, for that i have another extension.
extension CGFloat {
static var random: CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}extension UIColor {
static var random: UIColor {
return UIColor(red: .random, green: .random, blue: .random, alpha: 1.0)
}
}
How to use it..??
Call the variable
view.backgroundColor = UIColor.random
Thank you for reading..🙏
