Search code examples
iosswiftuinavigationcontrolleruinavigationitem

Reuse navigation bar button


In my project I have UINavigationController with three embedded UIViewControllers. On the first one I add balanceLabel and refreshButton to navigation bar. When click on button first view controller send url request and show return value on label.

@IBAction func refreshButtonAction(_ sender: UIBarButtonItem) {

let operation = GetInfoOperation(...)

operation.completionBlock = { [weak self] in

  DispatchQueue.main.async {

    guard let balance = operation.output?.value?.balance else { return }
    self?.balanceLabel.text = balance
    let significantDigits = Int(Double(balance.toInt64!) * pow(10, -10))

  }
}
queue.addOperation(operation)

}

How can I get the same behaviour on other ViewControllers without duplicate @IBAction func refreshButtonAction(_ sender: UIBarButtonItem) in each ViewController?


Solution

  • you can archive this by extension, using inheritance,

    create the view controller you want with all the common feature you want and then instead of inheriting directly from UIViewController inherit from that base viewController

    your base controller BaseViewController

    class BaseViewController: UIViewController {
       //all comman functionallity 
       //add your button here 
    }
    
    class ChildOneViewController: BaseViewController {
       //this class will get all the functionality from BaseViewController
       //you can access the BaseViewController button here
       //add function for ChildOneViewController
    }
    
     class ChildtwoViewController: BaseViewController {
       //this class will get all the functionality from BaseViewController
       //you can access the BaseViewController button here
       //add function for ChildtwoViewController
    }