首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 程式碼關閉 UIAlertView 的正確方法

     編輯:程式設計綜合問答

UIAlertView(iOS 9 棄用,建議改用 UIAlertController)無自動關閉機制,需呼叫實例方法 dismissWithClickedButtonIndex:animated: 以程式碼強制關閉。常用於網路逾時、權限變更、App 進入背景等需主動關閉提示的場景。

標準關閉代碼


// 保留 alert 實例參考
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"錯誤"
                                                message:@"連線失敗"
                                               delegate:self
                                      cancelButtonTitle:@"確定"
                                      otherButtonTitles:nil];
[alert show];

// 任意時刻程式碼關閉(如收到網路回應、ViewController 消失)
[alert dismissWithClickedButtonIndex:alert.cancelButtonIndex animated:YES];

關鍵參數說明

參數說明
buttonIndex模擬使用者點擊的按鈕索引,cancelButtonIndex 代表取消鍵,會觸發 delegate 的 alertView:clickedButtonAtIndex:
animated是否播放淡出動畫,建議 YES 保持體驗一致

現代替代:UIAlertController (iOS 8+)


UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"錯誤"
                                                               message:@"連線失敗"
                                                        preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:YES completion:nil];

// 程式碼關閉
[self dismissViewControllerAnimated:YES completion:nil];
// 或 alert.dismissViewControllerAnimated:YES completion:nil]; // iOS 10+

常見應用場景

  • 網路請求逾時:發送請求後啟動 NSTimer,逾時執行 dismiss 並顯示錯誤。
  • 權限狀態變更:使用者在設定頁開啟權限返回 App,關閉引導提示。
  • App 生命週期:applicationWillResignActive 中關閉所有彈窗,避免回前景時殘留。
  • 單例提示管理:封裝 AlertManager 統一持有/關閉提示,避免重疊。

注意事項

  • 持有 UIAlertView 強引用(屬性或變數),否則 ARC 可能提前釋放導致 dismiss 呼叫無效。
  • 多執行緒環境確保在主執行緒呼叫 UI 方法。
  • UIAlertView 已棄用,新專案請直接使用 UIAlertController。

掌握程式碼控制提示框關閉,能構建更智能、使用者友善的互動流程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved