我想显示来自viewDidLoad()
ViewController.m
方法而不是viewDidAppear()
方法的提醒消息。
这是我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
//A SIMPLE ALERT DIALOG
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"My Title"
message:@"Enter User Credentials"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action")
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
NSLog(@"Cancel action");
}];
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"OK", @"OK action")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(@"OK action");
}];
[alert addAction:cancelAction];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
}
我收到此错误:
警告:尝试在视图不在窗口层次结构中的
<UIAlertController: 0x7fbc58448960>
上显示<ViewController: 0x7fbc585a09d0>
!
答案 0 :(得分:21)
确定不是错误,问题在于viewDidLoad
视图层次结构未完全设置。如果使用viewDidAppear
,则设置层次结构。
如果你真的想在viewDidLoad
中调用此警报,可以通过将演示文稿调用包装在此GCD块中来引起轻微延迟,等待下一个运行循环,但我建议你不要(它很难看)。
dispatch_async(dispatch_get_main_queue(), ^ {
[self presentViewController:alert animated:YES completion:nil];
});
答案 1 :(得分:9)
将此调用移至viewDidAppear:方法。
答案 2 :(得分:0)
您必须嵌入导航控制器并显示控制器
- (void)viewDidLoad {
[super viewDidLoad];
//A SIMPLE ALERT DIALOG
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"My Title"
message:@"Enter User Credentials"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action")
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
NSLog(@"Cancel action");
}];
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"OK", @"OK action")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(@"OK action");
}];
[alert addAction:cancelAction];
[alert addAction:okAction];
[self.navigationController presentViewController:alert animated:NO completion:nil];
// [self presentViewController:cameraView animated:NO completion:nil]; //this will cause view is not in the window hierarchy error
}
或
[self.view addSubview:alert.view];
[self addChildViewController:alert];
[alert didMoveToParentViewController:self];
答案 3 :(得分:-1)
Swift 3 iOS 10,我使用操作队列将更新UI的代码块放到主线程上。
import UIKit
class ViewController2: UIViewController {
var opQueue = OperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
let alert = UIAlertController(title: "MESSAGE", message: "HELLO WORLD!", preferredStyle: UIAlertControllerStyle.alert)
// add an action (button, we can add more than 1 buttons)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.opQueue.addOperation {
// Put queue to the main thread which will update the UI
OperationQueue.main.addOperation({
self.present(alert, animated: true, completion: nil)
})
}
}
}
简而言之,我们正在使用异步。这允许警报消息按预期显示(即使我们在viewDidLoad()中)。