Search code examples
iosiphoneswiftxcode6nsattributedstring

NSAttributedString issues in Swift


I'm getting issues with NSAtrributedString no matter which path I take and can't seem to figure out what the issue is.

With the code below I get: Cannot invoke 'init' with an argument list of type '(string: StringLiteralConvertible, attributes: $T6)'

let cancelButtonTitle = NSAttributedString(string: "CANCEL", attributes: [NSFontAttributeName: buttonFont, NSForegroundColorAttributeName: UIColor.whiteColor()])

Any ideas where the issue lies? I've tried in xcode 6.1 and 6.2.


Solution

  • NSFontAttributeName should be set to a UIFont object.

    let buttonFont = UIFont.systemFontOfSize(10)
    
    let cancelButtonTitle = NSAttributedString(string: "CANCEL",
        attributes: [NSFontAttributeName: buttonFont,
            NSForegroundColorAttributeName: UIColor.whiteColor()])
    

    or if you are using a specific font.

    if let buttonFont = UIFont(name: "Your Font", size: 10) {
    
        let cancelButtonTitle = NSAttributedString(string: "CANCEL",
        attributes: [NSFontAttributeName: buttonFont,
            NSForegroundColorAttributeName: UIColor.whiteColor()])
    }
    

    because UIFont(name:,size:) constructor returns an optional, you need to unwrap it before using it in NSAttributedString