Cannot assign value of type 'UIColor' to type 'CGColor?

-1

Attempt

I just added the extention to convert hex to UIcolor

extension UIColor {
    convenience init(hexString: String, alpha: CGFloat = 1.0) {
        let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }
    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
        return String(format:"#%06x", rgb)
    }
}

Usage

When I started to use it

profileImage.layer.borderColor = UIColor(hexString: "#3f3f3f")


Result

I kept getting

Cannot assign value of type 'UIColor' to type 'CGColor?'

enter image description here

Any hints for me ? I'm on XCode 10 Swift 4.

ios
swift
colors
hex
uicolor
asked on Stack Overflow Oct 16, 2018 by kyo

2 Answers

0

Replace this

profileImage.layer.borderColor  = UIColor(hexString: "#3f3f3f")

with

profileImage.layer.borderColor  = UIColor(hexString: "#3f3f3f").cgColor 

see here in Docs

var borderColor: CGColor? { get set }
answered on Stack Overflow Oct 16, 2018 by Sh_Khan
0
profileImage.layer.borderColor  = UIColor(hexString: "#3f3f3f").cgColor

would work as it would convert UIColor to CGColor.

answered on Stack Overflow Oct 16, 2018 by Md. Ibrahim Hassan • edited Oct 16, 2018 by rmaddy

User contributions licensed under CC BY-SA 3.0