Vlad Alexeev
Vlad Alexeev

Reputation: 2204

Attributed text swift how to change color of unattributed text

I try to make a night/day option for my app. I have a text like "<font color="#aa2c2c">Red text</font>then back to normal " . So I need red to stay red and change only unattributed color.

Here's what I try:

    text.enumerateAttributesInRange(NSRange(0..<text.length), options: []) { (attributes, range, _) -> Void in
        for (attribute, object) in attributes {
            NSLog("attr \(attribute) object \(object)")                
            }
        }
    }

So, log shows me something like "attr NSColor object UIDeviceRGBColorSpace 0 0 0 1" or "attr NSStrokeColor object UIDeviceRGBColorSpace 0 0 0 1". That seems to be that black text which I need to change to white.

So I put this in the loop:

        if object.name!.containsString("0 0 0 1"){
            text.setAttributes(NSForegroundColorAttributeName, value: UIColor.whiteColor() , range: range)
        }

I'm not sure if it's the best decision, but I got error : Extra argument 'value' in call. What's wrong with this and what is the best way to substitute color of non-attributed text only?

Upvotes: 1

Views: 7574

Answers (1)

gurmandeep
gurmandeep

Reputation: 1247

 let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here."
 let linkTextWithColor = "click here"

 let range = (text as NSString).rangeOfString(linkTextWithColor)

 let attributedString = NSMutableAttributedString(string:text)
 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

 self.helpText.attributedText = attributedString

or

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

Upvotes: 4

Related Questions