Search code examples
iosswiftnsattributedstring

NSAttributed string not working in swift


I am trying to use attributed string to customize a label but getting weird errors in swift.

func redBlackSubstring(substring: String) {
    self.font = UIFont(name: "HelveticaNeue", size: 12.0)
    var theRange: Range<String.Index>! = self.text?.rangeOfString(substring)
    var attributedString = NSMutableAttributedString(string: self.text!)

    let attribute = [NSForegroundColorAttributeName as NSString: UIColor.blackColor()]
    attributedString.setAttributes(attribute, range: self.text?.rangeOfString(substring))
    self.attributedText = attributedString
}

I have also tried using the below code

func redBlackSubstring(substring: String) {
    self.font = UIFont(name: "HelveticaNeue", size: 12.0)
    var theRange: Range<String.Index>! = self.text?.rangeOfString(substring)
    var attributedString = NSMutableAttributedString(string: self.text!)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: self.text?.rangeOfString(substring))
    self.attributedText = attributedString
}

In both the cases, getting weird errors "Can not invoke 'setAttributes' with an argument list of type '([NSString : ..."

I have tried most of the solutions available on stack overflow and many other tutorials but, all of them resulting in such errors.


Solution

  • The main culprit is Range. Use NSRange instead of Range. One more thing to note here is, simply converting self.text to NSString will give you error for forced unwrapping.

    Thus, use "self.text! as NSString" instead.

    func redBlackSubstring(substring: String) {
        self.font = UIFont(name: "HelveticaNeue", size: 12.0)!
        var range: NSRange = (self.text! as NSString).rangeOfString(substring)
        var attributedString = NSMutableAttributedString(string: self.text)
        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: range)
        self.attributedText = attributedString
    }