我有两个 UIViewController,当我单击一个按钮时,它会从第一个 View Controller 转到第二个 View Controller 。在此之前,我动画了一个 UIView 以移动到另一个地方。关闭第二个 View Controller 后,我想将第一个 View Controller 中的 UIView 移回原来的位置。但是,当我在关闭第二个 View Controller 后从第二个 View Controller 调用一个函数来为第一个 View Controller 中的 UIview 设置动画时,它无法获取 UIView 的属性,也无法对其执行任何操作。我想是因为第一个 UIViewController 还没有加载。那是问题所在吗?我应该如何解决这个问题?
最佳答案
有两种解决方案可以使用快速闭包
class FirstViewController: UIViewController {
@IBAction func start(_ sender: Any) {
guard let secondController = self.storyboard?.instantiateViewController(withIdentifier: "SecondController") as? SecondController else { return }
secondController.callbackClosure = { [weak self] in
print("Do your stuff")
}
self.navigationController?.pushViewController(secondController, animated: true)
}
}
//----------------------------
class SecondController: UIViewController {
var callbackClosure: ((Void) -> Void)?
override func viewWillDisappear(_ animated: Bool) {
callbackClosure?()
}
}
或者你可以使用协议(protocol)
class FirstViewController: UIViewController {
@IBAction func start(_ sender: Any) {
guard let secondController = self.storyboard?.instantiateViewController(withIdentifier: "SecondController") as? SecondController else { return }
secondController.delegate = self
self.navigationController?.pushViewController(secondController, animated: true)
}
}
extension ViewController : ViewControllerSecDelegate {
func didBackButtonPressed(){
print("Do your stuff")
}
}
//--------------------------
protocol SecondControllerDelegate : NSObjectProtocol {
func didBackButtonPressed()
}
class SecondController: UIViewController {
weak var delegate: SecondControllerDelegate?
override func viewWillDisappear(_ animated: Bool) {
delegate?.didBackButtonPressed()
}
}
关于ios - 解散第二个 Controller 后如何在第一个 Controller 中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46871803/