How to set target and action for UIBarButtonItem at runtime?


To create a bar button action at run time we’ll need to go through a few steps. First of all let’s start by creating a new project.

Once you have created the project, go to it’s storyboard directly, select the ViewController and Embed it into a navigation controller.

Now go to the respective View controller class and inside it, we’ll perform some steps that will add a button to the navigation bar on run time.

Create an objc function that should be called when the button is pressed.

@objc func barButtonAction() {
   print("Button pressed")
}

Now add the viewWillLayoutSubviews method to your class.

First, we’ll create a bar button now.

let barButton = UIBarButtonItem()

Then we’ll give some name to this bar code

barButton.title = "custom"

Now we’ll add a custom action to this bar code, and give it the target of self

barButton.action = #selector(barButtonAction)
barButton.target = self

Now we’ll add this button to the navigation bar of our application.

self.navigationItem.setLeftBarButton(barButton, animated: true)

This is how the complete code looks like now When we run the above code on our device this is how it looks.

override func viewWillLayoutSubviews() {
   let barButton = UIBarButtonItem()
   barButton.title = "custom"
   barButton.action = #selector(barButtonAction)
   barButton.target = self
   self.navigationItem.setLeftBarButton(barButton, animated: true) }
   @objc func barButtonAction() {
   print("Button pressed") }

when we press the button on the navigation bar multiple times, below is the result that’s produced.

 

Updated on: 30-Jul-2019

940 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements