0

我意识到我的 UIBarButtonItem(左右按钮)的颜色行为并不理想。

如果我按住右边的 UIBarButton(见视频),那么颜色会从浅黄色变为灰色的深黄色。

但是,我想要一个保持相同浅黄色的解决方案,无论任何按钮选择、按住等。按钮颜色应始终保持相同的浅黄色。

我怎样才能做到这一点?

这是在模拟器中完成的视频:(您可以清楚地看到单击-n-按住会导致颜色变化。即使按住不放也保持浅黄色的解决方案是什么??)

在此处输入图像描述

这是代码:

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

2 回答 2

1

请尝试这种方法:

// 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() 中调用此方法

于 2019-09-16T13:48:37.860 回答
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")
    }

于 2019-09-16T13:35:02.733 回答