我在Swift 3项目的主要ViewController.swift文件中有以下代码。当我调用showAgreement()时,它会毫无错误地执行,但不会显示任何UI。如何才能显示UIAlertController?
我的ViewController.swift文件定义为:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.showAgreement()
}
var alert: UIAlertController?
func showAgreement() {
alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert!.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert!.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}
}))
self.present(alert!, animated: true, completion: {
})
}
}
控制台输出显示:
警告:尝试显示其视图不在窗口层次结构中!