我使用此代码在我的应用程序中为navigationController
中的UIBarButtonItem
使用moonIcon Font,例如Awesome字体
let menuButton = UIBarButtonItem(title: publicSVGAssets().menu, style: UIBarButtonItemStyle.plain, target: self, action: #selector(menuAction))
menuButton.setTitleTextAttributes(NSDictionary(dictionary: [NSAttributedStringKey.font : UIFont(name: "icomoon", size: 25)!, NSAttributedStringKey.foregroundColor : UIColor.red]) as? [NSAttributedStringKey : Any], for: [])
self.navigationItem.rightBarButtonItem = menuButton
最佳答案
它可能很简单,因为仅当按钮的状态为 .normal
(如您指定)时才应用字体属性。
您可能需要指定按钮的所有状态都应用这些标题文本属性,如下所示:
let title = publicSVGAssets().menu
let style = UIBarButtonItemStyle.plain
let selector = #selector(menuAction)
let menuButton = UIBarButtonItem(title: title, style: style, target: self, action: selector)
let font = UIFont(name: "icomoon", size: 25)
let attributesDictionary: [NSAttributedStringKey: Any]? = [NSAttributedStringKey.font: font!, NSAttributedStringKey.foregroundColor : UIColor.red]
menuButton.setTitleTextAttributes(attributesDictionary, for: .normal)
menuButton.setTitleTextAttributes(attributesDictionary, for: .selected)
menuButton.setTitleTextAttributes(attributesDictionary, for: .highlighted)
self.navigationItem.rightBarButtonItem = menuButton
点击按钮将更改其状态。这可能就是为什么当您点击它时您会看到它改变图标。
注意:如果您需要在其他状态下显示按钮(例如禁用
),您还需要为该状态分配相同的标题文本属性。
...例如:
menuButton.setTitleTextAttributes(attributesDictionary, for: .disabled)
(注意:这与 @Satish 给出的答案类似)。
关于ios - bar按钮项目文本在moonIcon中选择时会改变,就像swift 4中的Font Awesome一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52721492/