Artem Bakanov
Artem Bakanov

Reputation: 260

Swift UIBarButtonItem with custom view disabled text color

I create a UIBarButtonItem with a custom view (UIButton) due to a complex design requirement. Below is a simplified version of my implementation. I set the baseForegroundColor of the UIButton, which works as expected. However, when an alert is shown, the UIBarButtonItem gets disabled, and the text color changes to light gray. I need the text color to remain the same at all times, but I can't find a way to achieve it. Could you please help me?

class ViewController: UIViewController {



    override func viewDidLoad() {

        super.viewDidLoad()

        navigationItem.rightBarButtonItem = createAddButton()

        let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: {_ in }))

        self.present(alert, animated: true, completion: nil)

    }



    func createAddButton() -> UIBarButtonItem {

        var configuration = UIButton.Configuration.plain()

        configuration.title = "TEST"

        configuration.baseForegroundColor = .red

        configuration.background.backgroundColor = .white

        let button = UIButton(configuration: configuration)

        let barButton = UIBarButtonItem(customView: button)

        return barButton

    }

}

Upvotes: 0

Views: 34

Answers (2)

Artem Bakanov
Artem Bakanov

Reputation: 260

After trying some random methods of UIButton, I found that it is enough to add:

button.tintAdjustmentMode = .normal

Upvotes: 1

khawar ali
khawar ali

Reputation: 339

you can use UIButton(type: .custom) to set the disabled color.

func createAddButton() -> UIBarButtonItem {
    let button = UIButton(type: .custom)
    button.setTitle("TEST", for: .normal)
    button.setTitleColor(.red, for: .normal) // normal color
    button.setTitleColor(.red.withAlphaComponent(0.3), for: .highlighted) // pressed color
    button.setTitleColor(.red, for: .disabled) // disabled color
    let barButton = UIBarButtonItem(customView: button)
    return barButton
}

OR for simple text, with different init method

func createAddButton() -> UIBarButtonItem {
    let button = UIBarButtonItem(title: "TEST", style: .plain, target: self, action: #selector(buttonTapped))
    button.tintColor = UIColor.systemRed
    return button
}

Upvotes: 0

Related Questions