Swift 3:如何将属性应用于字符串的各个部分



所以我在 Swift 2 中使用的方法不再有效,因为 Swift 3 在字符串索引和范围方面发生了变化。以前我有

func configureLabel(defaultColor: UIColor, highlightColor: UIColor, boldKeyText: Bool) {
    if let index = self.text?.characters.indexOf(Character("|")) {
        self.text = self.text!.stringByReplacingOccurrencesOfString("|", withString: "")
        let labelLength:Int = Int(String(index))! // Now returns nil
        var keyAttr: [String:AnyObject] = [NSForegroundColorAttributeName: highlightColor]
        var valAttr: [String:AnyObject] = [NSForegroundColorAttributeName: defaultColor]
        if boldKeyText {
            keyAttr[NSFontAttributeName] = UIFont.systemFontOfSize(self.font.pointSize)
            valAttr[NSFontAttributeName] = UIFont.systemFontOfSize(self.font.pointSize, weight: UIFontWeightHeavy)
        }
        let attributeString = NSMutableAttributedString(string: self.text!)
        attributeString.addAttributes(keyAttr, range: NSRange(location: 0, length: (self.text?.characters.count)!))
        attributeString.addAttributes(valAttr, range: NSRange(location: 0, length: labelLength))
        self.attributedText = attributeString
    }
}

基本上我可以采用像"名字:|Gary Oak">,并将 | 字符之前和之后的所有部分都设置为不同的颜色,或者将其部分加粗,但我上面评论的行不再返回值,这会破坏之后的其他所有内容。关于如何做到这一点的任何想法?

在 Swift 3 中,你可以使用这样的东西:

func configureLabel(defaultColor: UIColor, highlightColor: UIColor, boldKeyText: Bool) {      
    if let index = self.text?.characters.index(of: Character("|")) {
        self.text = self.text!.replacingOccurrences(of: "|", with: "")
        let position = text.distance(from: text.startIndex, to: index)
        let labelLength:Int = Int(String(describing: position))!
        var keyAttr: [String:AnyObject] = [NSForegroundColorAttributeName: defaultColor]
        var valAttr: [String:AnyObject] = [NSForegroundColorAttributeName: highlightColor]
        if boldKeyText {
            keyAttr[NSFontAttributeName] = UIFont.systemFont(ofSize: self.font.pointSize)
            valAttr[NSFontAttributeName] = UIFont.systemFont(ofSize: self.font.pointSize, weight: UIFontWeightHeavy)
        }
        let attributeString = NSMutableAttributedString(string: self.text!)
        attributeString.addAttributes(keyAttr, range: NSRange(location: 0, length: (self.text?.characters.count)!))
        attributeString.addAttributes(valAttr, range: NSRange(location: 0, length: labelLength))
        self.attributedText = attributeString
    }
}

主要思想是使用 let position = text.distance(from: text.startIndex, to: index) 得到的不是字符串位置的整数表示,而是字符串索引值。使用 text.distance(from: text.startIndex, to: index) 您可以找到字符串索引的 int 位置

最新更新