[英]How to pause the code and wait for an answer from UIAlert on Swift using UIAlertController
[英]Why is UIAlertController not pausing code while it waits for answer?
我的理解是 UIAlertController 在呈现后的正常行为是等待用户响应,换句话说就是暂停其他代码。
在这种情况下,当用户单击保存时,应该会出现一个 UIAlertController,询问用户有关保存的问题,然后等待响应。 但是,代码仍在继续,并且警报控制器在大约一秒钟后被解除。
以下内容可能有什么问题,阻止代码暂停并导致警报在大约一秒钟后消失?
-(void) save {
if (listView.text.length>=1) {
[self fireAlertNewOrUpdate];
}
// save everything else
//dismiss view controller - this line of code may be dismissing the alert controller...
}
-(void) fireAlertNewOrUpdate {
UIAlertController *listAlert = [UIAlertController alertControllerWithTitle:@"Save list as new?" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yes = [UIAlertAction
actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[self saveNewList];
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Update existing" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action)
{
[self updateExisting];
}];
[listAlert addAction:cancel];
[listAlert addAction:yes];
if ([listAlert respondsToSelector:@selector(setPreferredAction:)]) {
[listAlert setPreferredAction:yes];
}
[self presentViewController:listAlert animated:YES completion:nil];
}
你自己给出了答案,只是你也对我们隐瞒了。 (幸运的是,您在评论中暗示了这一点。)这是因为您在save
省略了一行代码,您在其中关闭了视图控制器。 该视图控制器是警报,因此警报会响应调用fireAlertNewOrUpdate
,然后立即再次消失。 实际上,您是一口气说“ present / dismiss
。
我的理解是 UIAlertController 在呈现后的正常行为是等待用户响应,换句话说,暂停其他代码
不,完全不正确。 事实上,恰恰相反。 即使出现警报,您的“其他代码”也会继续运行。 在 iOS 编程中基本上没有任何代码会自发地“暂停”。 出于这个原因,在你调用present
来呈现一个视图控制器之后,在该代码中什么都不做是很常见的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.