小编典典

类型'String'的值没有成员'stringByTrimmingCharactersInSet'

swift

将项目转换为swift 3后,Value of type 'String' has no member 'stringByTrimmingCharactersInSet'在此代码块的第一行出现以下错误:

extension UIColor {
    convenience init (hex:String) {
        var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercased() // error appears on this line

        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)


        self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
    }
}

我猜该错误'stringByTrimmingCharactersInSet'是由.. 语法变化引起的,对此的更正是什么?


阅读 380

收藏
2020-07-07

共1个答案

小编典典

新语法如下:

var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

作为建议,您无需指定该cString字符串,因为假定您要为其分配值。

2020-07-07