2017-02-03 16 views
0

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 

    } 
} 

基本的に私は「ファーストネーム:|ゲイリーオーク」のような文字列を取ることができるだろう持っていたをして前後のすべての部分を持っているし|文字は色が違うか太字にしていますが、私が上でコメントした行は値を返しません。これを行う方法に関するアイデア?あなたは、文字列の位置の整数表現が、文字列のインデックス値を持っていない使用してlet position = text.distance(from: text.startIndex, to: index)こと

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 

    } 

} 

主なアイデア:

答えて

1

はスウィフト3では、あなたはこのようなものを使用することができます。 text.distance(from: text.startIndex, to: index)を使用すると、文字列のint位置を見つけることができます。インデックス