2015-02-05 25 views
1

无论我采用哪种路径,都无法找出NSAtrributedString的问题。Swift中的NSAttributedString问题

有了下面的代码我得到:Cannot invoke 'init' with an argument list of type '(string: StringLiteralConvertible, attributes: $T6)'

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

任何想法,其中的问题所在?我已经在xcode 6.1和6.2中试过了。

+1

可以请你告诉你定义buttonFont变量的行之前解开呢? – rakeshbs

+0

看到如何使用NSAttributedString http://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label-swift/27728516#27728516 –

回答

2

NSFontAttributeName应该设置为UIFont对象。

let buttonFont = UIFont.systemFontOfSize(10) 

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

,或者如果您使用的是特定的字体。

if let buttonFont = UIFont(name: "Your Font", size: 10) { 

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

因为UIFont(name:,size:)构造函数返回一个optional,您需要使用它NSAttributedString

+0

我正在使用特定的字体: '让buttonFont = UIFont(名称:“AvenirNext-Bold”,size:25)' 这样就修好了。 – Frolie