【swift3.0】NSMutableAttributedStringで文字の色を部分的に切り替える


文字の途中の色を変えたい場合

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
override func viewDidLoad() {

    myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
    // set label Attribute
    labName.attributedText = myMutableString
    super.viewDidLoad()
}

もっと分割したいときは条件を追加していけば良い。

 myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))

実際に使うときには自分で細かい条件は変更した。

var myMutableString = NSMutableAttributedString()
var myString = "文章文章文章文章文章文章文章文章文章文章文章文章文章文章文章"
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont.hiraginoSans(ofSize: 12)])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: Color.gray, range: NSRange(location:7,length:9))
profileLabel.attributedText = myMutableString

スタイルを変えたりするのは条件部分を変えれば良い。

参考