LoginSignup
10
8

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-07-31

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

B9UVg.png

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()
}

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

eHVh1.png

 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

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

参考

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8