** IOS 開發(fā)中 Whose view is not in the window hierarchy 錯誤的解決辦法 **
在 IOS 開發(fā)當中經(jīng)常碰到 whose view is not in the window hierarchy 的錯誤沦疾,該錯誤簡單的說第队,是由于 "ViewController" 還沒有被加載,就調(diào)用該 ViewController 或者 ViewController 內(nèi)的方法時凳谦,就會報這個錯誤。
在不同地方調(diào)用 ViewController家凯,解決的方法也不太一樣剔交。
1. 在 一個 ViewController 里面調(diào)用另外一個 ViewController 是出現(xiàn)這個錯誤:
該錯誤一般是由于在 viewDidLoad 里面調(diào)用引起的,解決辦法是轉(zhuǎn)移到 viewDidAppear 方法里面
2. 在 AppDelegate.m 中調(diào)用遇到這個錯誤
解決辦法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)
}