在夫特-5.0的UIBarButtonItem颜色设置(UIBarButtonItem color

2019-10-28 17:21发布

我意识到,我的UIBarButtonItem的(左右键)色彩的行为不理想。

如果我按住右UIBarButton(见视频),然后从浅黄色的颜色变化来gray'isch暗黄色。

不过,我想,保持相同的浅黄色,无任何按键选择,按和保持的事,等按钮颜色应始终保持相同的浅黄色的解决方案。

我怎样才能做到这一点?

这里是视频模拟器完成:(你可以清楚地看到,点击正保持引起颜色变化是什么时保持的浅黄色甚至解决按下并保持??)

这里是代码:

@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)
}

Answer 1:

这里是你如何可以通过包装一个普通按钮为您barButton项目达到预期的效果。

    private let normalButton: UIButton = {
        let normalButton = UIButton()
        normalButton.frame = CGRect(x: 0, y: 0, width: 80, height: 30)
        normalButton.setTitle("Apply", for: .normal)
        normalButton.setTitleColor(.yellow, for: .normal)
        normalButton.isUserInteractionEnabled = true
        return normalButton
    }()

    private lazy var applyRightBarButtonItem: UIBarButtonItem = {
        // Wrap your button as UIBarButtonItem
        return UIBarButtonItem(customView: normalButton)
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Important for detecting taps
        normalButton.addTarget(self, action: #selector(normalButtonTapped), for: .touchUpInside)
        // Set your right bar button ( You can do the same for the left one)
        self.navigationItem.rightBarButtonItem = applyRightBarButtonItem

    }

    @objc private func normalButtonTapped() {
        // TODO: - Handle tap
        print("Button Tapped")
    }



Answer 2:

请试试这个方法:

// 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调用这个方法()



文章来源: UIBarButtonItem color setting in Swift-5.0