Presenting UIAlertController from UINavigationItem extension

78 Views Asked by At

I'm trying to add the same right bar button on multiple view controllers so I made an extension to UINavigationItem. My extension:

extension UINavigationItem{

func barButton() {
    let barButton = UIBarButtonItem()
    barButton.image = UIImage(systemName: "person.fill")
    barButton.tintColor = .white
    barButton.action = #selector(barButtonClicked)
    barButton.target = self
    self.rightBarButtonItem = barButton
}

@objc func barButtonClicked() {
    let alertController = UIAlertController()
    var action = UIAlertAction(title: "Log Out", style: .destructive) { action in
        print("logout")
    }
    alertController.addAction(action)
    action = UIAlertAction(title: "History", style: .default, handler: { action in
        print("history")
    })
    alertController.addAction(action)
}

}

I'm calling barButton function in different viewControllers with self.navigationItem.barButton() in viewDidLoad and it works but I don't know how to present this alert without self.present() pointing to specific controller. Thank you for your help.

1

There are 1 best solutions below

0
Noor Ahmed Natali On

You can write a selector function from a view controller

func barButton(func: Selector) {
let barButton = UIBarButtonItem()
barButton.image = UIImage(systemName: "person.fill")
barButton.tintColor = .white
barButton.action = func
barButton.target = self
self.rightBarButtonItem = barButton }

and write a @objc function in a view controller and if you need to write the same function for all. you can create a function in UIViewController Extension