2015-02-05 28 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