Swift-5.0 中的 UIBarButtonItem 颜色设置 [英] UIBarButtonItem color setting in Swift-5.0
问题描述
我意识到我的 UIBarButtonItem(左右按钮)的颜色行为不符合预期.
I realised that the color-behaviour of my UIBarButtonItem's (left and right buttons) is not as desired.
如果我按住右侧的 UIBarButton(参见视频),则颜色会从浅黄色变为灰色的深黄色.
If I press and hold the right UIBarButton (see video), then the color changes from light-yellow to gray'isch dark-yellow.
但是,我想要一个保持相同浅黄色的解决方案,无论选择任何按钮、按住等操作.按钮颜色应始终保持相同的浅黄色.
However, I would like a solution that keeps the same light-yellow color, no matter of any button selection, press-and-hold, etc. The button color should always stay the same light-yellow.
我怎样才能做到这一点?
How can I achieve this ?
这是在模拟器中完成的视频:(您可以清楚地看到,单击-按住会导致颜色变化.即使按住也保持浅黄色的解决方案是什么??)
Here is the video done in Simulator: (you can clearly see that click-n-hold causes a color-change. what is the solution to keep the light-yellow color even when press-and-hold ??)
代码如下:
@IBOutlet weak var btnCancel: UIBarButtonItem!
@IBOutlet weak var btnApply: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
btnCancel.title = "Cancel".localized
btnApply.title = "Apply".localized
navigationItem.title = "Filter".localized
let attributes: [NSAttributedString.Key : Any] = [ .font: UIFont(name: "Avenir-Heavy", size: 14)!, .foregroundColor: UIColor.yellow]
navigationItem.rightBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)
navigationItem.rightBarButtonItem?.setTitleTextAttributes(attributes, for: .selected)
navigationItem.rightBarButtonItem?.setTitleTextAttributes(attributes, for: .highlighted)
navigationItem.rightBarButtonItem?.setTitleTextAttributes(attributes, for: .focused)
}
推荐答案
请试试这个方法:
// MARK:- Custom BarButton Appearance
private extension YourViewController {
func setupBarButtonAppearance() {
let color = UIColor.yellow
let font = UIFont(name: "Avenir-Heavy", size: 14)!
let customAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [YourViewController.self])
customAppearance.setTitleTextAttributes([
NSAttributedString.Key.foregroundColor : color,
NSAttributedString.Key.font : font], for: .normal)
customAppearance.setTitleTextAttributes([
NSAttributedString.Key.foregroundColor : color,
NSAttributedString.Key.font : font], for: .highlighted)
}
}
只需在 viewDidLoad() 中调用此方法
simply call this method in your viewDidLoad()
这篇关于Swift-5.0 中的 UIBarButtonItem 颜色设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!