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

问题描述:

因此,我在Swift 2中使用的方法不再适用,因为Swift 3中有关字符串索引和范围的更改。以前我有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 

    } 
} 

基本上,我将能够获得一个字符串像“名字:|加里橡树”并有前后所有零件|字符是不同的颜色,或者使它的一部分变成粗体,但是我上面评论的那一行不再返回一个值,之后会打破所有其他的值。任何想法如何做到这一点?

在斯威夫特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位置索引