Home > Enterprise >  How to add an action to a UIBarButton programmatically?
How to add an action to a UIBarButton programmatically?

Time:11-14

I've been creating a small iOS app using Swift just for fun, and I have already decided that I want a notification box (a bell-shaped button you can click on to check if there's any notification), and I also wanted to add the bell-shaped button to every screen.
So, I decided to make a base view controller and have other view controllers inherit it. However, that's when my problem arose; I have no idea how to add an action func for that button. Since I create the bell-shaped button programmatically, I cannot just ^ drag and create a new IBaction.

I found this post: link, but this is for a UIButton, not for a UIBarButton, and it didn't work for me.

Sorry for this long question. Below is a simple, one-sentenced question:
MY PROBLEM
How can I add an action to a UIBarButton programmatically?

UPDATE Here's my base view controller:

import UIKit

class BaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add a notification button
        let notificationButton = UIBarButtonItem(image: UIImage(systemName: "bell.fill"))
        notificationButton.tintColor = .black
        
        self.navigationItem.rightBarButtonItem = notificationButton
    }
    
    
    
}

UPDATE2

Here's my new code:

import UIKit

class BaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add a notification button
        let notificationButton = UIBarButtonItem(
            image: UIImage(systemName: "bell.fill"),
            style: .plain,
            target: self,
            action: #selector(notificationButtonPressed)
        )
        
        notificationButton.tintColor = .black
        
        self.navigationItem.rightBarButtonItem = notificationButton
    }
    
    @objc func notificationButtonPressed() {
        print("Hello")
    }
}

CodePudding user response:

You can pass a target-action pair to the initialiser of UIBarButtonItem:

let barButton = UIBarButtonItem(
    image: UIImage(systemName: "bell.fill"), 
    style: .plain, 
    target: self, action: #selector(buttonTapped)
)

// somewhere in your view controller:

@objc func buttonTapped() {
    // do something when the bar button is tapped
}

See the documentation here.

This is similar to UIButton's addTarget(_:action:for:_) method, if you are familiar with that.

  • Related