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