请问老师在swift 语言中怎样直接使用16进制的色值

来源:9-3 Swift-更加灵活的枚举使用方式

恩格贝

2015-03-11 17:33

请问老师在swift 语言中怎样直接使用16进制的色值

写回答 关注

5回答

  • Kalpa晓
    2016-04-06 22:52:20
    已采纳

    func UIColorFromRGB (hex:String) -> UIColor {

            var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

            

            if (cString.hasPrefix("#")) {

                cString = (cString as NSString).substringFromIndex(1)

            }

            let rString = (cString as NSString).substringToIndex(2)

            let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)

            let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)

            

            var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;

            NSScanner(string: rString).scanHexInt(&r)

            NSScanner(string: gString).scanHexInt(&g)

            NSScanner(string: bString).scanHexInt(&b)

            return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))

        }


    eg:

    self.setTitleColor(UIColorFromRGB("0xec8c00"), forState: .Selected)


    恩格贝

    非常感谢!

    2016-04-27 16:03:32

    共 1 条回复 >

  • 拾稻子
    2016-11-23 15:35:43

    已用粗体标出。

  • 拾稻子
    2016-11-23 15:35:05

    func UIColorFromRGB (hex:String) -> UIColor {       
            var cString:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
            if (cString.hasPrefix("#")) {        
                cString = (cString as NSString).substring(from: 1)
            }    
            let rString = (cString as NSString).substring(to: 2)
            let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
            let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
            var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
            Scanner(string: rString).scanHexInt32(&r)
            Scanner(string: gString).scanHexInt32(&g)
            Scanner(string: bString).scanHexInt32(&b)
            return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1)) 
        }
    这些需要改动的。

  • 拾稻子
    2016-11-23 15:31:59

    亲测,可以使用谢谢!不过swift3的语法略微有些变化,需要稍微修改下。

  • 白云蓝天
    2016-02-17 19:32:18

    这个还需要转换成UIColor里面三色才能使用

玩儿转Swift

这套教程比任何的Swift中文教程深入,并且演示示例更丰富

57181 学习 · 511 问题

查看课程

相似问题