Efe Helvaci Efe Helvaci - 5 months ago 59
Swift Question

How to format attributed strings in swift?

I'm working on a notification page where inputs are mostly come from a JSON file and I need to combine them with localized strings. This is how it should look:

Sketch design

As can be predicted colored parts come from the JSON file and rest of it comes from Localizable.strings. This is what comes from Localizable file:

"%@ has joined %@"

If I use
String(format: String, [...])
I have a plain black text and I cant specify the parts needs to be colored.

I need the same feature for
but it doesn't have this method.

So how can I format attributed strings?

Answer Source

Check following example:

var myMutableString = NSMutableAttributedString()

myMutableString = NSMutableAttributedString(string: "Your full label textString")

myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: CGFloat(17.0))!
        , NSForegroundColorAttributeName : UIColor(red: 232 / 255.0, green: 117 / 255.0, blue: 40 / 255.0, alpha: 1.0)], range: NSRange(location:12,length:8)) // What ever range you want to give

yourLabel.attributedText = myMutableString

Or another way:

To change the colour of a length of text you need to know the start and end index of the coloured-to-be characters in the string e.g.

var main_string = "Hello World"
var string_to_color = "World"

var range = (main_string as NSString).rangeOfString(string_to_color)

Then you convert to attributed string and use 'add attribute' with NSForegroundColorAttributeName:

var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor() , range: range)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download