How to set the action for a UIBarButtonItem in Swift

前端 未结 5 2108
余生分开走
余生分开走 2020-12-12 19:51

How can the action for a custom UIBarButtonItem in Swift be set?

The following code successfully places the button in the navigation bar:

var b = UIB         


        
5条回答
  •  北海茫月
    2020-12-12 20:38

    May this one help a little more

    Let suppose if you want to make the bar button in a separate file(for modular approach) and want to give selector back to your viewcontroller, you can do like this :-

    your Utility File

    class GeneralUtility {
    
        class func customeNavigationBar(viewController: UIViewController,title:String){
            let add = UIBarButtonItem(title: "Play", style: .plain, target: viewController, action: #selector(SuperViewController.buttonClicked(sender:)));  
          viewController.navigationController?.navigationBar.topItem?.rightBarButtonItems = [add];
        }
    }
    

    Then make a SuperviewController class and define the same function on it.

    class SuperViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
                // Do any additional setup after loading the view.
        }
        @objc func buttonClicked(sender: UIBarButtonItem) {
    
        }
    }
    

    and In our base viewController(which inherit your SuperviewController class) override the same function

    import UIKit
    
    class HomeViewController: SuperViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
        }
    
        override func viewWillAppear(_ animated: Bool) {
            GeneralUtility.customeNavigationBar(viewController: self,title:"Event");
        }
    
        @objc override func buttonClicked(sender: UIBarButtonItem) {
          print("button clicked")    
        } 
    }
    

    Now just inherit the SuperViewController in whichever class you want this barbutton.

    Thanks for the read

提交回复
热议问题