Swift 3 NSAttributedString multiple attributes

user2206906 picture user2206906 · Nov 24, 2016 · Viewed 26.6k times · Source

just started swift 3 and I have problems with swift syntax.

i'm trying to display a simple NSAttributedString.

so 1st I set my attributes :

let attributeFontSaySomething : [String : AnyObject] = [NSFontAttributeName : UIFont.fontSaySomething()]
let attributeColorSaySomething : [String : AnyObject] = [NSForegroundColorAttributeName : UIColor.blue]

Then I create my string :

let attStringSaySomething = NSAttributedString(string: "Say something", attributes: self.attributeFontSaySomething)

What i would like to do is to create the string with my 2 attributes not only just one. But when i do :

let attStringSaySomething = NSAttributedString(string: "Say something", attributes: [self.attributeFontSaySomething, self.attributeColorSaySomething])

Xcode tells me I can't and want me to change this for a literal dictionary.

How can I create my string with the 2 attributes without using a NSMutableAttributedString ?

Answer

vadian picture vadian · Nov 24, 2016

The main issue is that you are passing an array [attr.. , attr...] rather than one dictionary.

You need to merge the two dictionaries into one

let attributeFontSaySomething : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 12.0)]
let attributeColorSaySomething : [String : Any] = [NSForegroundColorAttributeName : UIColor.blue]

var attributes = attributeFontSaySomething
for (key, value) in attributeColorSaySomething {
    attributes(value, forKey: key)
}

let attStringSaySomething = NSAttributedString(string: "Say something", attributes: attributes)

However it might be easier to create the dictionary literally:

let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName : UIColor.blue]