UIColor greatest practices in Swift

0/5 No votes

Report this app

Description

[ad_1]

Study what are colour fashions, the best way to convert hex values to UIColor and again, generate random colours, the place to seek out lovely palettes.

UIKit

What are colour fashions and colour areas?

A colour mannequin is a technique of describing a colour.

  • RGB – Purple+Inexperienced+Blue
  • HSB – Hue+Saturation+Brightness

There are a number of different colour fashions, however if you’re coping with iOS colours you need to be conversant in these two above. Often you’ll work with the RGBA & HSBA colour fashions that are principally the identical as above prolonged with the alpha channel the place the letter A stands for that. ๐Ÿ˜‰

A colour house is the set of colours which may be displayed or reproduced in a medium (whether or not saved, printed or displayed). For instance, sRGB is a specific set of intensities for crimson, inexperienced and blue and defines the colours that may be reproduced by mixing these ranges of crimson, inexperienced and blue.

Sufficient from the speculation, let’s do some colour magic! ๐Ÿ’ซ๐Ÿ’ซ๐Ÿ’ซ


Tips on how to work with UIColor objects utilizing RGBA and HSBA values in Swift?

Do you bear in mind the outdated Paint program from old-school Home windows instances?

I’ve used Microsoft Paint loads, and I liked it. ๐Ÿ˜…

Again then with none CS data I used to be at all times questioning in regards to the numbers between 0 and 255 that I needed to choose. If you’re working with RGB colours you normally outline your colour the identical means, besides that in iOS the values are between 0 and 1, however that is only a totally different illustration of the fraction of 255.

So you may make a colour with RGB codes utilizing the identical logic.

UIColor(crimson: CGFloat(128)/CGFloat(255),
        inexperienced: CGFloat(128)/CGFloat(255),
        blue: CGFloat(128)/CGFloat(255),
        alpha: 1)

UIColor(crimson: 0.5, inexperienced: 0.5, blue: 0.5, alpha: 1)

See? Fairly straightforward, huh? ๐Ÿ‘

Alternatively you should use HSB values, virtually the identical logic applies for these values, besides that hue goes from 0 ’til 360 (due to the precise colour wheel), nonetheless saturation and brightness are measured in a “p.c like” format 0-100, so it’s a must to take into consideration these numbers in case you map them to floating level values.

UIColor(hue: CGFloat(120)/CGFloat(360), saturation: 0.5, brightness: 0.5, alpha: 1)
UIColor(hue: 0.3, saturation: 0.5, brightness: 0.5, alpha: 1)

Now let’s reverse the state of affairs and let me present you the best way to get again these parts from an precise UIColor occasion with the assistance of an extension.

public extension UIColor {
    public var rgba: (crimson: CGFloat, inexperienced: CGFloat, blue: CGFloat, alpha: CGFloat) {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, inexperienced: &g, blue: &b, alpha: &a)
        return (r, g, b, a)
    }

    public var hsba: (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) {
        var h: CGFloat = 0
        var s: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
        return (h, s, b, a)
    }
}

So right here it’s the best way to learn the crimson, inexperienced blue slash hue saturation brightness and alpha parts from a UIColor. With this little neat extension you may merely get the element values and use them by means of their correct names.

UIColor.yellow.rgba.crimson
UIColor.yellow.hsba.hue

Tips on how to convert HEX colours to RGB and vica versa for UIColor objects in Swift?

iOS developer 101 course, first questions:

  • How the fuck can I create a UIColor from a hex string?
  • Tips on how to convert a hex colour to a UIColor?
  • Tips on how to use a hext string to make a UIColor?

Okay, perhaps these will not be the primary questions, however it’s undoubtedly inside widespread ones. The reply is fairly easy: by means of an extension. I’ve a very nice resolution in your wants, which can deal with many of the circumstances like utilizing only one, 2, 3 or 6 hex values.

public extension UIColor {

    public comfort init(hex: Int, alpha: CGFloat = 1.0) {
        let crimson = CGFloat((hex & 0xFF0000) >> 16) / 255.0
        let inexperienced = CGFloat((hex & 0xFF00) >> 8) / 255.0
        let blue = CGFloat((hex & 0xFF)) / 255.0

        self.init(crimson: crimson, inexperienced: inexperienced, blue: blue, alpha: alpha)
    }

    public comfort init(hex string: String, alpha: CGFloat = 1.0) {
        var hex = string.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if hex.hasPrefix("#") {
            let index = hex.index(hex.startIndex, offsetBy: 1)
            hex = String(hex[index...])
        }

        if hex.depend < 3 {
            hex = "(hex)(hex)(hex)"
        }

        if hex.vary(of: "(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", choices: .regularExpression) != nil {
            if hex.depend == 3 {

                let startIndex = hex.index(hex.startIndex, offsetBy: 1)
                let endIndex = hex.index(hex.startIndex, offsetBy: 2)

                let redHex = String(hex[..<startIndex])
                let greenHex = String(hex[startIndex..<endIndex])
                let blueHex = String(hex[endIndex...])

                hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
            }

            let startIndex = hex.index(hex.startIndex, offsetBy: 2)
            let endIndex = hex.index(hex.startIndex, offsetBy: 4)
            let redHex = String(hex[..<startIndex])
            let greenHex = String(hex[startIndex..<endIndex])
            let blueHex = String(hex[endIndex...])

            var redInt: CUnsignedInt = 0
            var greenInt: CUnsignedInt = 0
            var blueInt: CUnsignedInt = 0

            Scanner(string: redHex).scanHexInt32(&redInt)
            Scanner(string: greenHex).scanHexInt32(&greenInt)
            Scanner(string: blueHex).scanHexInt32(&blueInt)

            self.init(crimson: CGFloat(redInt) / 255.0,
                      inexperienced: CGFloat(greenInt) / 255.0,
                      blue: CGFloat(blueInt) / 255.0,
                      alpha: CGFloat(alpha))
        }
        else {
            self.init(crimson: 0.0, inexperienced: 0.0, blue: 0.0, alpha: 0.0)
        }
    }

    var hexValue: String {
        var colour = self

        if colour.cgColor.numberOfComponents < 4 {
            let c = colour.cgColor.parts!
            colour = UIColor(crimson: c[0], inexperienced: c[0], blue: c[0], alpha: c[1])
        }
        if colour.cgColor.colorSpace!.mannequin != .rgb {
            return "#FFFFFF"
        }
        let c = colour.cgColor.parts!
        return String(format: "#%02Xpercent02Xpercent02X", Int(c[0]*255.0), Int(c[1]*255.0), Int(c[2]*255.0))
    }
}

Right here is how you should use it with a number of enter variations:

let colours = [
    UIColor(hex: "#cafe00"),
    UIColor(hex: "cafe00"),
    UIColor(hex: "c"),
    UIColor(hex: "ca"),
    UIColor(hex: "caf"),
    UIColor(hex: 0xcafe00),
]
let values = colours.map { $0.hexValue }
print(values) 

As you may see I’ve tried to duplicate the habits of the CSS guidelines, so you’ll have the liberty of much less characters if a hext string is like #ffffff (you should use simply f, as a result of # is non-obligatory). Additionally you may present integers as effectively, that is only a easy “overloaded” comfort init technique.

Additionally .hexValue will return the string illustration of a UIColor occasion. ๐Ÿ‘๐Ÿ‘๐Ÿ‘


Tips on how to generate a random UIColor in Swift?

That is additionally a quite common query for newbies, I do not actually wish to waste the house right here by deep rationalization, arc4random() is simply doing it is job and the output is a pleasant randomly generated colour.

public extension UIColor {
    public static var random: UIColor {
        let max = CGFloat(UInt32.max)
        let crimson = CGFloat(arc4random()) / max
        let inexperienced = CGFloat(arc4random()) / max
        let blue = CGFloat(arc4random()) / max

        return UIColor(crimson: crimson, inexperienced: inexperienced, blue: blue, alpha: 1.0)
    }
}

Tips on how to create a 1×1 pixel huge UIImage object with a single strong colour in Swift?

I am utilizing this trick to set the background colour of a UIButton object. The explanation for that is state administration. When you press the button the background picture can be darker, so there can be a visible suggestions for the person. Nevertheless by setting the background colour straight of a UIButton occasion will not work like this, and the colour will not change in any respect on the occasion. ๐Ÿ‘†

public extension UIColor {
    public var imageValue: UIImage {
        let rect = CGRect(origin: .zero, measurement: CGSize(width: 1, top: 1))
        UIGraphicsBeginImageContext(rect.measurement)
        let context = UIGraphicsGetCurrentContext()!
        context.setFillColor(self.cgColor)
        context.fill(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}

The snippet above will produce a 1×1 pixel picture object from the supply colour. You should use that anywere, however right here is my instance with a button background:

button.setBackgroundImage(UIColor.crimson.imageValue, for: .regular)

On-line colour palettes

You possibly can’t discover the fitting colour? No downside, these hyperlinks will assist you to to decide on the correct one and to get some inspiration. Additionally if you’re searching for flat UI colours or materials design colours these are the fitting hyperlinks the place it’s best to head first.

A private factor of mine: expensive designers, please by no means ever attempt to use materials design rules for iOS apps. Thanks. HIG


Convert colours on-line

Lastly there are some nice on-line colour converter instruments, if you’re searching for an awesome one, it’s best to attempt these first.


Managing UIColors

In case your app goal is iOS 11+ you should use asset catalogs to prepare your colour palettes, but when you’ll want to go beneath iOS 11, I might counsel to make use of an enum or struct with static UIColor properties. These days I am normally doing one thing like this.

class App {
    struct Coloration {
        static var inexperienced: UIColor { return UIColor(hex: 0x4cd964) }
        static var yellow: UIColor { return UIColor(hex: 0xffcc00) }
        static var crimson: UIColor { return UIColor(hex: 0xff3b30) }
    }

    
}

App.Coloration.yellow

Often I am grouping collectively fonts, colours and so forth inside structs, however this is only one means of doing issues. You can too use one thing like R.swift or something that you simply desire.

That is it for now, I believe I’ve lined many of the primary questions on UIColor.

Be happy to contact me if in case you have a subject or suggestion that you simply’d prefer to see lined right here within the weblog. I am at all times open for brand new concepts. ๐Ÿ˜‰

[ad_2]

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.