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 *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 並顯示錯誤。applicationWillResignActive 中關閉所有彈窗,避免回前景時殘留。AlertManager 統一持有/關閉提示,避免重疊。UIAlertView 強引用(屬性或變數),否則 ARC 可能提前釋放導致 dismiss 呼叫無效。UIAlertView 已棄用,新專案請直接使用 UIAlertController。掌握程式碼控制提示框關閉,能構建更智能、使用者友善的互動流程。