iOS 개발 시 Label에 색을 넣을 때...한정적 색만 존재하여 여러가지 색상을 넣기 애매


RGB 색상을 넣기 위하여 구글 검색 시작 !


Swift 1.0을 1.2를 거쳐 2.0에 맞는 코드 찾음.


관련 질문을 stackoverflow에서 찾고

http://stackoverflow.com/questions/24074257/how-to-use-uicolorfromrgb-value-in-swift

댓글에서 아래 github를 찾고

https://gist.github.com/arshad/de147c42d7b3063ef7bc

github에서 댓글로 2.0에 맞는 코드를 발견 ㅎ


결국 만들어 낸 코드 !

extension UIColor {
    convenience init(hexString: String) {
        let hex = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
        var int = UInt32()
        NSScanner(string: hex).scanHexInt(&int)
        let a, r, g, b: UInt32
        switch hex.characters.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        case 8: // ARGB (32-bit)
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            (a, r, g, b) = (1, 1, 1, 0)
        }
        self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
    }
}

코드 사용법은

cell.Label.textColor = UIColor(hexString : "A9A9A9")

RGB코드는 여기 참고 http://www.javascripter.net/faq/rgbtohex.htm


+ Recent posts