我想显示来自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>
,其视图不在窗口层次结构中!
确定不是错误,问题是在viewDidLoad
中视图层次结构未完全设置。如果使用viewDidAppear
,则设置层次结构。
如果你真的想在viewDidLoad
中调用这个警报你可以通过将你的演示调用包装在这个GCD块中来引起轻微延迟,等待下一个运行循环,但是我建议你不要(它很难看)。
dispatch_async(dispatch_get_main_queue(), ^ {
[self presentViewController:alert animated:YES completion:nil];
});
将此调用移至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.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];
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()中)。