0

I have navigationBarItems and I'm trying to change background color of UIButton when user taps it.

Here is my code of navigationBarItems:

private func createNavigationBarItems() {
    let boldButton = UIButton(type: .custom)
    boldButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    boldButton.setTitle("B", for: .normal)
    boldButton.setTitleColor(UIColor.systemBlue, for: .normal)
    boldButton.tag = TextStyle.bold.rawValue
    boldButton.addTarget(self, action: #selector(insertStyle(_:)), for: .touchUpInside)
    let boldButtonItem = UIBarButtonItem(customView: boldButton)

    let italicButton = UIButton(type: .custom)
    italicButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    italicButton.setTitle("I", for: .normal)
    italicButton.setTitleColor(UIColor.systemBlue, for: .normal)
    italicButton.tag = TextStyle.italic.rawValue
    italicButton.addTarget(self, action: #selector(insertStyle(_:)), for: .touchUpInside)
    let italicButtonItem = UIBarButtonItem(customView: italicButton)
 navigationItem.leftBarButtonItems = [
      boldButtonItem,
      italicButtonItem]
}

I'm calling this method in viewDidLoad().

This is the button action func:

 @objc func insertStyle(_ sender: UIButton) {
        guard let textView = textView else { return }
        let style = TextStyle(rawValue: sender.tag)
        switch style {
        case .bold:
          updateText(type: .bold, editor: textView.editor)
          
        case .italic:
          updateText(type: .italic, editor: textView.editor)
      
    }

How do I change the UIButton background color when user taps on button and clear the background color when tapped again?

sdev dev
  • 37
  • 7
  • Some ideas: https://stackoverflow.com/questions/4012664/uibarbuttonitem-highlighted-color – Shawn Frank Mar 30 '22 at 18:00
  • Also, have properties to save the state of your button if this is part of your app logic. It is better to not rely on views properties. – Ptit Xav Mar 31 '22 at 06:57

0 Answers0