web-dev-qa-db-ja.com

テキスト属性辞書でUIFontをインスタンス化するときにエラーが発生しました

UIBarButtonItemのフォントを次のように設定しようとしています。

let barButton = UIBarButtonItem.appearance()
barButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "AvenirNext", size: 15], forState: UIControlState.Normal)

ただし、次のようなコンパイラエラーがスローされます。

引数リストタイプ '($ T7、forState:UIControlState) `で' init 'を呼び出すことはできません

それが何を意味するのか私にはわかりません。私も試しました

barButton.titleTextAttributesForState(UIControlState.Normal) =[NSFontAttributeName...]` 

しかし、それは割り当て可能ではないようです

どうすればこれを解決できますか?

14
Eilon

UIFontの初期化子は、フォント名のスペルミスなどが原因で失敗する可能性があるため、オプションを返します。

あなたはそれを開梱してチェックする必要があります:

if let font = UIFont(name: "AvenirNext", size: 15) {
    barButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
}

Swift用に更新

if let font = UIFont(name: "AvenirNext", size: 15) {
    barButton.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)
}
27
zisoft

カスタムフォントの設定は、fontプロパティとtitleプロパティがないため、少し注意が必要です。この次の答えがお役に立てば幸いです。

let font = UIFont(name: "<your_custom_font_name>", size: <font_size>)
var leftBarButtonItem = UIBarButtonItem(title: "<font_hex_code>", style: UIBarButtonStyle.Plain, target: self, action: "buttonClicked:")
leftBarButtonItem.setTitleTextAttributes([NSFontAttributeName:font!], forState: UIControlState.Normal)
self.navigationItem.leftBarButtonItem = leftBarButtonItem
2
Sandeep Ankam
if let font : UIFont = UIFont(name: "Roboto-Regular", size: 15)
        {
            cancelBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
            doneBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)

        }
1
A.G

With Swift 4

NSFontAttributeNameは非推奨です、NSAttributedStringKey値を使用して属性を設定できます。

if let fontStyle = UIFont(name: "HelveticaNeue-Light", size: 19) {
 navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: fontStyle]

}

0
Ekra