2

I find using hex codes file defining colours much easier than rgba, so I researched about how to use a converter from hex code to UIColor. I first created a new file called UIColorUtility and added:

import Foundation
import UIKit

extension UIColor {
    public convenience init?(hexString: String) {
        let r, g, b, a: CGFloat

        if hexString.hasPrefix("#") {
            let start = hexString.startIndex.advancedBy(1)
            let hexColor = hexString.substringFromIndex(start)

            if hexColor.characters.count == 8 {
                let scanner = NSScanner(string: hexColor)
                var hexNumber: UInt64 = 0

                if scanner.scanHexLongLong(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255

                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }

        return nil
    }
}

Then in my viewController, I tried to change this bit

.SelectionIndicatorColor(UIColor(red: 0.8, green: 0.153, blue: 0.106, alpha: 1.0)),

into this bid:

.SelectionIndicatorColor(UIColor(hexString: "#929292"))!,

It first forced me to unwrap it, and then started giving me error..

Type of expression is ambiguous without more context

What am I doing wrong? Also, just out of curiosity, how can I set the alpha too after applying hexString approach?

senty
  • 12,385
  • 28
  • 130
  • 260
  • http://stackoverflow.com/questions/28696862/what-is-the-best-shortest-way-to-convert-a-uicolor-to-hex-web-color-in-swift/28697136?s=1|0.1545#28697136 – Leo Dabus Jan 18 '16 at 02:16
  • 1
    http://stackoverflow.com/questions/27698533/how-do-i-pick-the-color-in-hexadecimal-form-or-rgb-form-instead-of-using-the-col/27698546?s=1|0.5785#27698546 – Leo Dabus Jan 18 '16 at 02:17
  • @Leo, I used [this approach](https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor), but why mine isn't working? – senty Jan 18 '16 at 02:22
  • I had to update the code to work with Swift 2. Try with the updated code – Leo Dabus Jan 18 '16 at 02:27
  • 1
    BTW your problem with that code was the parameter input length that needs to be 8 characters and you were passing only 6 – Leo Dabus Jan 18 '16 at 03:47
  • .SelectionIndicatorColor(UIColor(hexString: "#929292"))! You try use RGB Value (6 symbols) but u code for correct work want 8 (RGBA color). set hex value as .SelectionIndicatorColor(UIColor(hexString: "#929292FF"))! – Vladyslav Feb 10 '17 at 14:34

0 Answers0