** IOS 开发中 Whose view is not in the window hierarchy 错误的解决办法 **
在 IOS 开发当中经常碰到 whose view is not in the window hierarchy 的错误,该错误简单的说,是由于 "ViewController" 还没有被加载,就调用该 ViewController 或者 ViewController 内的方法时,就会报这个错误。
在不同地方调用 ViewController,解决的方法也不太一样。
1. 在 一个 ViewController 里面调用另外一个 ViewController 是出现这个错误:
该错误一般是由于在 viewDidLoad 里面调用引起的,解决办法是转移到 viewDidAppear 方法里面
2. 在 AppDelegate.m 中调用遇到这个错误
解决办法1:
UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topRootViewController.presentedViewController)
{
topRootViewController = topRootViewController.presentedViewController;
}
//[topRootViewController presentViewController:yourController animated:YES completion:nil];
//or
[topRootViewController myMethod];
解决办法2:
UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
LoginViewController* loginViewController = [mainstoryboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
[self.window makeKeyAndVisible];
//[LoginViewController presentViewController:yourController animated:YES completion:nil];
//or
[LoginViewController myMethod];
** 警告框要写在viewDidAppear中 **
override func viewDidAppear(_ animated: Bool){
super.viewDidAppear(animated)
let alert = UIAlertController(title: "警告", message: "警告信息", preferredStyle: .alert)
alert.addTextField(configurationHandler: {
(textfield:UITextField!) -> Void in
textfield.placeholder = "输入姓名"
})
alert.addTextField { (textfield2:UITextField!)-> Void in
textfield2.placeholder = "输入密码"
}
let cancleAct = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let okAct = UIAlertAction(title: "确定", style: .default, handler: {
action in
print("确定.............>")
})
//按钮使用“告警”样式(文字颜色变红,用来来警示用户)
// let detAct = UIAlertAction(title: "删除", style: .destructive, handler: {
// action in
// print("删除")
// })
alert.addAction(cancleAct)
alert.addAction(okAct)
// alert.addAction(detAct)
self.present(alert, animated: true, completion: {
print("弹出警告框")
})
}
//两秒钟后自动消失
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
self.presentedViewController?.dismiss(animated: false, completion: nil)
}