ios - 解散第二个 Controller 后如何在第一个 Controller 中调用函数

标签 ios swift uiviewcontroller

我有两个 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/

相关文章:

swift - 如何在 Swift 中创建一个通用枚举 Equatable?

ios - 将应用上传到 App Store 后,Firebase 号码身份验证不起作用

ios - 限制用户可以在 Parse 上存储的图像数量

ios - 滚动后 UIScrollView 中对象的可见坐标

UITableViewCell 中的 iOS 容器 View

ios - 如何从不在 Storyboard 中但以编程方式创建的 View Controller 呈现 "main" Storyboard 中的 View Controller ?

objective-c - 子类 UIView 或 UIViewController

ios - 将 UISwitch 状态从一个 View Controller 传递到另一个 View Controller

iphone - 将对象从NSMutableDictionary添加到NSMutableArray

ios - 如何检测 UIWebView 何时完全完成加载?