Search code examples
swiftrangeswift4nsmutableattributedstring

Variable sized range for NSMutableAttributedString


I have a label with the string shown below. I would like secondVariable to be a different color. I think I understand how to change the color. My problem is getting the range of secondVariable.

let str = "\(firstVariable) some random text \(secondVariable)"

let secondVariableRange = str.range(???) 
let secondVariableNSRange = NSRange(secondVariableRange, in: str)

let attributedString = NSMutableAttributedString.init(string: 
    "\(firstVariable) some random text \(secondVariable)")

attributedString.addAttribute(.foregroundColor, value: UIColor.white, 
    range: NSRange(secondVariableNSRange, in: attributedString)

Solution

  • There's a simpler approach than dealing with ranges. Build up your attributed string in pieces.

    let attributedString = NSMutableAttributedString(string: 
    "\(firstVariable) some random text ")
    let attrs: [NSAttributedStringKey : Any] = [ .foregroundColor: UIColor.white ]
    let secondString = NSAttributedString(string: "\(secondVariable)", attributes: attrs)
    attributedString.append(secondString)
    

    But if you really want to get the range, use:

    let secondVariableRange = (str as NSString).range(of: "\(secondVariable)")