![](/img/trans.png)
[英]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.