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

时间:2017-02-03 21:44:07

标签: swift3 nsattributedstring nsrange

因此,我在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

    }
}

基本上我可以使用“First Name:| Gary Oak”之类的字符串,并且 | 字符之前和之后的所有部分都是不同的颜色,或者将其中的一部分加粗,但我上面评论的行不再返回一个值,之后会破坏其他所有内容。关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:1)

在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)的主要思想不是字符串位置的整数表示而是字符串Index值。使用text.distance(from: text.startIndex, to: index),您可以找到字符串Index

的int位置