ios – 常用导航按钮动作另一个类

我为所有View控制器制作了通用导航栏.但是我需要按下那些调用我正在调用公共导航栏的操作

@objc extension UIViewController {

@objc func setBarButtonItem(titleLabel: String) 
{
let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 200 + 4, height: 38))

 let Nextbtn = UIButton(type: .custom)
 Nextbtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
Nextbtn.addTarget(self, action: #selector(NextButtonClicked), for: .touchUpInside)

 view.addSubview(Nextbtn)
 self.navigationItem.setLeftBarButton(UIBarButtonItem(customView: view), animated: true)

   /*
  @objc func NextButtonClicked()
    {
   }*/

 }
 }

呼叫控制器—> setBackBarButton( “你好……”)
如果我在这个类上创建了按钮动作方法,则调用Button.但是我想在这个调用Calling Controller类上制作按钮动作方法func NextButtonClicked(),或者我们可以访问这个类上的按钮动作的任何方法.

 @objc func NextButtonClicked()
{
}

最佳答案 您只需创建BaseViewController而不是扩展,并允许所有ViewControllers继承此BaseViewController

BaseViewController:

import UIKit
class BaseViewController: UIViewController {

    typealias CompletionBarButtonClicked = (()-> Void)
    var completionBarItemClicked:CompletionBarButtonClicked?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @objc func setBarButtonItem(titleLabel: String, completion :@escaping CompletionBarButtonClicked)
    {

        self.completionBarItemClicked = completion
        let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 200 + 4, height: 38))

        let Nextbtn = UIButton(type: .custom)
        Nextbtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        Nextbtn.addTarget(self, action: #selector(NextButtonClicked), for: .touchUpInside)

        view.addSubview(Nextbtn)
        self.navigationItem.setLeftBarButton(UIBarButtonItem(customView: view), animated: true)

    }

    @objc func NextButtonClicked()
    {
        if let completionHandler = completionBarItemClicked{
            completionHandler()
        }
    }

}

示例ViewController:

import UIKit
class ViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        self.setBarButtonItem(titleLabel: "test") {

            /// your action There
        }

    }
}
点赞