[英]How do I change the font of a UIBarButtonItem in Swift?
我通常是一名耐心的調試器,花費大量時間在Google上搜索並尋找問題的答案。 但是,我的耐心已經耗盡,我開始相信這是完全不可能的。
但是,我正在使用導航欄在iOS應用程序上工作,並且選擇在整個用戶界面中使用“ Optima”字體。 我已經能夠更改導航欄標題的字體,以及初始視圖上的自定義導航欄按鈕。 但是,在任何后續視圖中,我的后退按鈕上的字體都是系統的默認字體。 對於我的一生,我找不到改變它的方法。
我已經嘗試過搜索中出現的所有內容,而我獲得的最接近的成功來自於本博文 。
下面的代碼對我有用,但是可以將后退按鈕當然更改為圖像,而不是按我希望的那樣更改字體 。
self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "Tab_Trophy")
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "Tab_Trophy")
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
(順便說一句,上面的代碼在我的后退按鈕會將用戶發送到的視圖的viewDidLoad()中)
無論如何,我也嘗試過在不同的地方使用下面的setTitleTextAttributes,但無濟於事。
setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Optima", size: 19.0)!], forState: .Normal)
所以我的問題是:能做到嗎? 還是應該使用所需字體的文本制作圖像並利用上面的代碼起作用?
以下代碼將更改頂部“導航欄”和底部“工具欄”項目的字體(UINavigationBar.appearance()。titleTextAttributes僅更改導航欄)。
筆記:
它使用以下命令設置導航欄字體:
navigationController.navigationBar.titleTextAttributes
它通過遍歷每個工具欄項並使用以下命令來設置工具欄項:
toolbarItem.setTitleTextAttributes
分享和享受。
var firstShow = false override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if firstShow { let navbarAttributes:[String:Any] let toolbarAttributes:[String:Any] if let font = UIFont(name: "AmericanTypewriter", size: 22.0) { navbarAttributes = [ NSFontAttributeName: font, NSForegroundColorAttributeName : UIColor.init(red:1.0, green:0, blue:0, alpha:1.0) ] toolbarAttributes = [ NSFontAttributeName: font ] } else { navbarAttributes = [ NSForegroundColorAttributeName : UIColor.init(red:1.0, green:0, blue:0, alpha:1.0) ] toolbarAttributes = [:] } navigationController?.navigationBar.titleTextAttributes = navbarAttributes if let toolbarItems = navigationController?.toolbar.items { for toolbarItem in toolbarItems { toolbarItem.setTitleTextAttributes(toolbarAttributes, for: .normal) toolbarItem.setTitleTextAttributes(toolbarAttributes, for: .disabled) } } firstShow = false } }
您可以為應用程序更改所有UIBarButtonItem
標簽的字體,您可以執行以下操作:
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName: UIFont(name: "Optima", size: 19.0)!
]
或者,如果您只想自定義單個標簽,則可以使用自定義按鈕,例如:
let button = UIButton()
// Customise button as required
let barButtonItem = UIBarButtonItem(customView: button)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.