【问题标题】:Getting destination ViewController from UIBarButtonItem?从 UIBarButtonItem 获取目标 ViewController?
【发布时间】:2019-04-27 14:41:48
【问题描述】:

我已经对 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
    }```

【问题讨论】:

  • 只需使用协议来获取回调。或者只是在前一个视图上重新加载 ViewWillAppear 方法。

标签: ios swift uibarbuttonitem


【解决方案1】:

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

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

让我们来个协议

protocol MyProtocol {
   func myFunction()
}

然后在ViewController2 中添加一个委托方法。假设在ViewController2,你得调用一个方法doMyWork,这里会做一些工作,那么你就得pop了。

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()
    }
}

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    相关资源
    最近更新 更多