我写了这个Xcode游乐场示例来演示我遇到的问题:
import PlaygroundSupport
import UIKit
let rootViewController = UIViewController()
rootViewController.view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 640.0, height: 640.0))
let navigationController = UINavigationController(rootViewController: rootViewController)
PlaygroundPage.current.liveView = navigationController
var alertController: UIAlertController! = UIAlertController(title: "Test", message: "This is a test", preferredStyle: .alert)
rootViewController.present(alertController, animated: true, completion: nil)
alertController.dismiss(animated: false, completion: nil)
rootViewController.presentedViewController
alertController = UIAlertController(title: "Another Test", message: "This is another test", preferredStyle: .alert)
rootViewController.present(alertController, animated: true, completion: nil)
rootViewController.presentedViewController!.title
我期望的是presentedViewController的标题为“另一个测试” 。标题实际上是“测试” ,表明导航控制器似乎仍然保留了原来显示的视图控制器,即使它已被关闭。
以编程方式为UINavigationController重置presentedViewController的正确方法是什么?
答案 0 :(得分:0)
您遇到的问题是动画需要花费时间,并且您要在第二个存在的动画调用之前先调用第二个存在的动画。即使有动画错误,这些调用也会花费一些时间。如果您使用完成关闭并将其链接在一起,则第二个警报将以正确的标题出现:
let rootViewController = UIViewController()
rootViewController.view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 640.0, height: 640.0))
let navigationController = UINavigationController(rootViewController: rootViewController)
PlaygroundPage.current.liveView = navigationController
var alertController: UIAlertController! = UIAlertController(title: "Test", message: "This is a test", preferredStyle: .alert)
rootViewController.present(alertController, animated: true) {
alertController.dismiss(animated: false) {
alertController = UIAlertController(title: "Another Test", message: "This is another test", preferredStyle: .alert)
rootViewController.present(alertController, animated: true, completion: nil)
}
}
如果您从Xcode运行原始代码,则会在控制台中看到以下消息:
Warning: Attempt to present <UIAlertController: 0x7fab67825200> on <TestProject.ViewController: 0x7fab66d0e090> while a presentation is in progress!
这是告诉您,发出第二个警报控制器的呼叫时,第一个警报控制器仍在显示。