swift2 我需要从索引1传递字符串值,我在swift 1.2中有代码,但在swift 3中无法获得所需的输出

ogsagwnx  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(201)
cString = cString.substring(from: advance(cString.startIndex, 1))

//我是swift 3的新手,请建议我在swift 3中替换此行。Xcode无法转换此行,并在使用未解析的标识符时出现错误。

nxowjjhe

nxowjjhe1#

雨燕3.0

您需要使用String方法(index(_:offsetBy:)来推进索引:

let index = cString.index(cString.startIndex, offsetBy: 1)       
cString = cString.substring(from: index)
py49o6xq

py49o6xq2#

我在我的一些项目中也使用了这个,您也可以使用它

func colorWithHexString (_ hex:String, alpha: Float) -> UIColor {

           var cString:String = hex.trim()

            if (cString.hasPrefix("#")) {
                cString = (cString as NSString).substring(from: 1)
            }

            if (cString.characters.count != 6) {
                return UIColor.gray
            }

            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(alpha))
    }

相关问题