Search code examples
iosswiftnsattributedstring

How to set NSAttributedString range?


A little confused with using the syntax. I know you are supposed to use NSFontAttributeName, however I don't know how to correctly specify the range.

I'm curious about two cases.

How do I specify the range for all characters in the text, and how do I specify the range as something like the first 10 characters.

Any suggestions?


Solution

  • Don't use magic numbers

    let baseString = "Don't use magic numbers."
    
    let attributedString = NSMutableAttributedString(string: baseString, attributes: nil)
    
    let dontRange = (attributedString.string as NSString).range(of: "Don't")
    attributedString.setAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)], range: dontRange)
    

    So meta