[英]Cannot Set Navigation Bar Font in Swift on Latest Xcode Version
在更新到Xcode 6.1之前,以下代碼運行正常,以便與iOS 8.1保持同步:
override func viewDidAppear(animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = "Home"
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34), NSForegroundColorAttributeName: UIColor.whiteColor()]
}
問題特別在NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34)
而我在這里得到的錯誤是:
! "Could not find an overload for 'init' that accepts the supplied arguments"
我在另一個StackOverflow問題上找到了這個原始代碼,它在預期之前正常工作,直到此更新(昨天下載)。 我的字體確實正確安裝。
我現在應該以不同的方式編寫此代碼,還是有一種全新的方式來設置導航欄字體?
謝謝!
哎呦。 我自己想出來了:
我聲明NSFontAttributeName后需要一個感嘆號,因為它需要一個類型“NSString!”。 也許它之前只需要一個“NSString”,但我現在沒有問題。
工作線:
NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 24)!
工作完整代碼:
override func viewDidAppear(animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = "Home"
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
}
現在看來似乎是一個愚蠢的問題。 希望這有助於其他人!
您正在使用UIFont(name:
因為它被定義為
init?(name fontName: String, size fontSize: CGFloat) -> UIFont
可用的初始化器從link中讀取更多內容。因此它返回可選。您需要打開它,因為它需要AnyObject
不是可選的。
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
謝謝Benji!
我稍微改了一下並將其應用到導航控制器的外觀屬性。
var navigationBarAppearance = UINavigationBar.appearance()
navigationBarAppearance.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "OpenSans", size: 16)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
最好將字體聲明為條件,如下所示:
if let font = UIFont (name: "AdobeArabic-BoldItalic", size: 20) {
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font]
}
這樣做,確保你的字體已經找到,我已經安裝了新的字體,並且在沒有條件的情況下使用它,如果它發出異常,則展開一個可選項。
override func viewWillLayoutSubviews() {
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName : UIFont(name: "Roboto-Regular", size: 14)!]
}
Swift 4.2
更改小標題 布局時向下滾動
override func viewDidAppear(animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = "Home"
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34), NSForegroundColorAttributeName: UIColor.whiteColor()]
}
改變大標題
override func viewDidAppear(animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = "Home"
self.navigationController?.navigationBar.largeTitleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34), NSForegroundColorAttributeName: UIColor.whiteColor()]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.