Search code examples
swiftswift5xcode11

UIBarButtonItem programmatically change color


I have this left UIBarButtonItem that performs like a switch, so I would like to make it gray when its off and the normal tint color when its on but I can't figure out how

Here is the code used to assign the buttons:

    doneHomeworksButton = UIBarButtonItem(image: doneHomeworksButtonImage, style: .plain, target: self, action: #selector(doneHomeworksClicked))
    addButton = UIBarButtonItem(image: plusButtonImage, style: .plain, target: self, action: #selector(plusButtonClicked))

    self.navigationItem.rightBarButtonItem = addButton
    self.navigationItem.leftBarButtonItem = doneHomeworksButton

This is the simulator (I want to change the left button)


Solution

  • This is the way, I use text instead of icon. you can user FM symbols of fontawesome or any other. And also you can change the image when button click

    class ViewController: UIViewController{
    
    
    var btnTick:UIBarButtonItem?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        btnTick  = UIBarButtonItem(title: "2", style: .plain, target: self, action: #selector(didClickedBtn(_ :)))
        btnTick?.tintColor = .blue
        navigationItem.leftBarButtonItem = btnTick
    }
    
    @objc func didClickedBtn(_ sender : UIBarButtonItem){
        sender.tintColor = .red
        view.layoutIfNeeded()
    }
    

    }

    enter image description here

    enter image description here