试图展示正在进行中的UIViewController! – 警告

假设一个新的iOS项目,只需要一个导航控制器(正确连线为入口点)和覆盖viewDidAppear()包含以下三行代码:

self.presentViewController(UIViewController(), animated: true, completion: nil) self.dismissViewControllerAnimated(true, completion: {}) self.presentViewController(UIViewController(), animated: true, completion: nil) 

执行时,该代码将引发一个警告:“尝试在演示文稿正在进行时呈现UIViewController!” 当试图呈现第二个控制器时。

问题:为了在调用另一个控制器之前正确地closures控制器,我到底错过了什么?

您需要在最初的presentViewController调用中添加某种延迟,如下所示:

 override func viewDidAppear(animated: Bool) { presentViewController(UIViewController(), animated: true) { () -> Void in self.delay(0.1, closure: { () -> () in self.dismissViewControllerAnimated(true, completion: nil) }) } } func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } 

看起来完成块在animation真正完成之前被调用。

假设你想要主控制器出现,提交一个控制器,解散控制器,再次出现并解散,那么你需要链接的行动,让他们按顺序发生。

为了防止它永久旋转,您还需要在主控制器第一次出现时才运行代码。

我不是快速的编码器,但像下面的东西应该工作。 有一个检查,以确保控制器正在呈现或被推动,然后运行序列使用每个操作完成开始下一个。 这个守卫应该确保在viewDidAppear被调用时,在每次解散之后,在这些场合它什么也不做。

 var firstTime = true; func presentThenDismiss(finalCompletion: (() -> Void)?) { presentViewController(UIViewController(), animated: true, completion : { [weak self] Void in // On completion of the present, we dismiss it dispatch_async(dispatch_get_main_queue(), { self?.dismissViewControllerAnimated(true, completion: { Void in // On completion of the dismiss, we present another finalCompletion!() }) }) }) } override func viewDidLoad() { super.viewDidLoad() // We only run the modal presentation code when being presented or // being pushed on, NOT when exposed by a model dismiss or pop // if (firstTime){ firstTime = false; self.presentThenDismiss { () -> Void in self.presentThenDismiss { () -> Void in } } } }