Search code examples
swiftnsattributedstring

Error creating attributed string- Swift


I am trying to create a attributed string and add it to a textfield along with a non attributed string. When I try to create the attributed string I get the exception :

Extra Argument String in Call.

Should be self explanatory but can't see it, code is

let theString : NSString = "Correct Answers: "
        let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
        let attributes : Dictionary = [NSFontAttributeName : labelFont]

//Exception thrown here
var attrString = NSAttributedString(string: "Foo", attributes:attributes);

textfield.text = attrString + "blah blah blah";

Thanks in advance.


Solution

  • You should unwrap your "labelFont" for the attributes.

    Also, you can't do

    attrString + "blah blah blah"
    

    because you can't directly add a String and a NSAttributedString.

    You can use a NSMutableAttributedString:

    let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
    let attributes = [NSFontAttributeName : labelFont!]
    var attrString = NSMutableAttributedString(string: "Foo", attributes: attributes)
    let newString = NSAttributedString(string: " blah blah blah")
    attrString.appendAttributedString(newString)
    println(attrString.description)