首页 > 解决方案 > bar Button Item text 在moonIcon中选择时会发生变化,如swift 4中的Font Awesome

问题描述

我使用此代码在我的应用程序中使用moonIcon Font like font UIBarButtonItemAwesomenavigationController

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

这会很好但问题是当用户选择按钮时,图标会改变,如下图所示 正如您在照片中看到的那样,右侧的条形按钮图像将变为问号但我希望该菜单图像像未选择按钮时一样

标签: iosswift4font-awesomeuibarbuttonitemuibarbuttonitemstyle

解决方案


它可能很简单,因为仅在按钮状态为.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

点击按钮将改变其状态。这可能就是您点击它时看到它更改图标的原因。

注意:如果您需要在其他状态下显示按钮(例如disabled),您还需要为该状态分配这些相同的标题文本属性。

...例如:

menuButton.setTitleTextAttributes(attributesDictionary, for: .disabled)

(注意:这与@Satish 给出的答案类似)。


推荐阅读