1

Here's my code

override func viewDidLoad() {
    super.viewDidLoad()

    let button1 = UIButton(frame: CGRect(x: 50, y: 50, width: 30, height: 30))
    button1.setTitle("hi", for: .normal)
    button1.setTitleColor(.blue, for: .normal)
    button1.setTitleColor(.black, for: .highlighted)
    button1.addTarget(self, action: #selector(self.barItem2Clicked(sender:)), for: .touchUpInside)
    button1.backgroundColor=UIColor.red

    let barButton1 = UIBarButtonItem(customView: button1)
    toolBar1.items?.append(barButton1)
}

method barItem2Clicked :

func barItem2Clicked(sender :Any?) {
    NSLog("hello")
}

I wanted to use UIButton add to UIToolBar, but the action of button1 can not be called, and the Highlighted effect is not shown too.

I clicked the button1 I just added, but the method barItem2Clicked never called.

Did I missed something?

Thanks

Loyoan
  • 23
  • 4
  • What happens when you add the target to the bar button item? What is the frame of the bar button item? – powerj1984 Aug 02 '17 at 15:13
  • You don't have a reference any more to your UIButton. See here: https://stackoverflow.com/a/45385689/6167296 – MH175 Aug 02 '17 at 15:21
  • 1
    Thank you guys, I think my code of the frame of the button is not the main reason of this problem, I changed the frame `CGRect(x: 50, y: 50, width: 30, height: 30)` to `CGRect(x: 0, y: 0, width: 50, height: 50)`, the toolBar can fix it automatically. – Loyoan Aug 02 '17 at 15:45

1 Answers1

0

Please make sure that the toolBar1 is connected I just tried with your code and it seems to be working.

enter image description here

sarosh mirza
  • 702
  • 5
  • 12
  • Did the method `barItem2Clicked` called? I builed a new project to test the code, and the method still can't be called. – Loyoan Aug 02 '17 at 15:41
  • Hi @Loyoan, the method gets called and it logs hello in the console. i checked it, may be if you want you can send me your code and i can see what is wrong there. you can push it to git so that i can check. – sarosh mirza Aug 02 '17 at 15:42
  • Thanks for you answer, i build several projects to test, i think it's a bug of Xcode. I open the first project and add some constrains to the toolbar then delete them all, then IT'S WORKING, i don't know why but it's finally working. Thank you for verifying my code. – Loyoan Aug 02 '17 at 17:36