ios - 从 UIBarButtonItem 获取目标 ViewController?

标签 ios swift uibarbuttonitem

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

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

    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
    }```

最佳答案

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

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

让我们制定一个协议(protocol)

protocol MyProtocol {
   func myFunction()
}

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

class ViewController2 {
    var delegate : MyProtocol?

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

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

现在viewController1已经接收委托(delegate),工作已经完成。

viewController1中,在barButtonItem中

class ViewController1 {

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

}

现在你必须实现协议(protocol)方法

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

关于ios - 从 UIBarButtonItem 获取目标 ViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55874977/

相关文章:

ios - ENsideSwiftMenu : how to use same Navigation Bar for all View Controllers

iphone - 从照片库访问特定相册中的照片

iphone - 重新启动应用程序时如何删除跳板图标上的角标(Badge)?

ios - 此编码器要求从 initWithCoder : 返回替换的对象

arrays - swift中连续数组的数据结构

iphone - UINavigationBar 左侧有两个按钮

ios - 使用 Unity 和 Vuforia 的 iOS 自定义相机权限通知

ios - Kingfisher nil 在展开可选值时

swift - 使用 GRDB,使用原始 sql 但以方便的形式使用结果?

ios - iOS 中的 SWRevealViewController 项目