iOS/코드조각

[iOS, Swift] UIColor hex값 사용하기(extension)

검은참깨두유vm 2022. 6. 22. 08:55
반응형

iOS 15, Xcode 13.31, Swift 5, UIKit 환경에서 진행했습니다.

extension UIColor {
	convenience init(hex: String) {
        let scanner = Scanner(string: hex)
        _ = scanner.scanString("#")
        
        var rgb:UInt64 = 0
        scanner.scanHexInt64(&rgb)
        
        let r = Double((rgb >> 16) & 0xFF) / 255.0
        let g = Double((rgb >> 8) & 0xFF) / 255.0
        let b = Double((rgb >> 0) & 0xFF) / 255.0
        self.init(red:r, green: g, blue: b, alpha: 1)
    }
}

 

사용법

UIColor(hex: "#707070")

 

 

반응형