-1

I created this right bar button item but when pressed nothing happens. The #selector is not firing, I know that the @objc function works.

let button = UIButton(type: .custom)
    button.setTitle("Uncheck All", for: .normal)
    button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
    button.setTitleColor(.bandzBlue(), for: .normal)
    button.layer.cornerRadius = 5
    button.backgroundColor = .white
    button.frame = CGRect(x: 0, y: 0, width: 92, height: 14)
    button.addTarget(self, action: #selector(self.addTapped), for: .touchUpInside)
    let barButton = UIBarButtonItem(customView: button)
    self.navigationItem.rightBarButtonItem = barButton
    @objc func addTapped() {
        stuff that works fine
    }
Matteo
  • 47
  • 9
  • I wrote the code exactly the same as your code and tested it. What's wrong with working? It works well. If the file you are creating the button and the addTapped function are in different files, you need to target them differently. – Byunsangjin Jul 18 '19 at 03:15
  • Yes they are in the same files, I have no idea either. – Matteo Jul 18 '19 at 03:27
  • Have posted an answer. In case it still doesn't work, please share your class here – Lokesh SN Jul 18 '19 at 04:05

2 Answers2

1

Maybe the rest of the instance haven't initialised at the time your code is executed. Have you tried doing this in viewDidLoad? If not, try doing that:

override func viewDidLoad() {
    super.viewDidLoad()

    configureYourBarButtonHere()
}

I remember seeing a lot of questions that highlight this issue, with this solution. Here are a couple ones I could find for now:

UIBarButtonItem selector not working

https://stackoverflow.com/a/49283627/9293498

Lokesh SN
  • 1,583
  • 7
  • 23
1

Try

 button.setTitleColor(UIColor.gray, for: .normal)

Instead of

button.setTitleColor(.bandzBlue(), for: .normal)

and UIButton(type: .system)