How to set target and action for UIBarButtonItem at runtime?

iOSiPhone/iPadMobile Development

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) = 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) = 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.


Published on 30-Jan-2019 04:51:16