首页 > 解决方案 > 从 UIBarButtonItem 获取目标 ViewController?

问题描述

我已经对 UIBarButtonItem 进行了编程,以便它在切换到上一个视图之前执行一些操作。我想知道如何从我的 UIBarButtonItem 中获取过渡场景的视图控制器?因此,场景 1 -> 场景 2(当前场景)-> 场景 1(单击 UIBarButtonItem 按钮后)

我试图将以前的场景变量(我需要)传递给当前场景以执行操作(感觉我不认为过渡场景正在实例化一个新视图,但这不起作用

    override func viewDidLoad() {
        super.viewDidLoad()
        loadTuple()
        let addButton: UIBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveExercise(_: )))
        self.navigationItem.setRightBarButton(addButton, animated: true)

    }
    @objc func saveExercise(_ sender: UIBarButtonItem) {
        self.addNewTupleToDB(element: self.getNewTuple())
        self.saveData()
        debugPrint("saveExercise")
        self.exerciseVCTableView?.reloadData() // tried to pass the table view from the previous scene to call here
        self.navigationController?.popViewController(animated: true)
        // Want to save reload the table data of the scene this button transitions to
    }```

标签: iosswiftuibarbuttonitem

解决方案


您可以使用委托模式来解决这个问题。委托模式是某种东西,将一些工作委托给其他人,并在委托完成后返回工作。

假设ViewController1有 UIBarButton , go to ViewController2,一些功能完成并返回ViewController1

让我们来个协议

protocol MyProtocol {
   func myFunction()
}

然后在ViewController2添加一个委托方法。假设在 中ViewController2,你必须调用一个方法doMyWork,并且会在这里完成一些工作,那么你必须弹出。

class ViewController2 {
    var delegate : MyProtocol?

    override func viewDidLoad() {
       super.viewDidLoad()
       doMyWork()
    }

    func doMyWork() {
       // my works 
       delegate?.myFunction()
       self.navigationController.popViewController()
    }
}

现在 viewController1 必须接收已完成的委托工作。

viewController1,在 barButtonItem

class ViewController1 {

    @objc func barButton(_sender : UIBarButton) {
       let viewController = ViewController2()
       viewController.delegate = self 
       self.naviagtionController.pushViewController(viewController, animated : true)
    }

}

现在你必须实现协议方法

extension ViewController1 : MyProtocol {
    func myFunction() {
       self.tableView.reloadData()
    }
}

推荐阅读