Search code examples
iosswiftuibarbuttonitemuitoolbar

The UIButton on UIToolBar seems to be not working


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


Solution

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

    enter image description here