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

iOS 開發:無按鈕 UIAlertView 的正確關閉方式

     編輯:程式設計綜合問答

場景描述

在網絡請求等異步操作期間,常需展示無按鈕的 UIAlertView 作為加載提示(通常內嵌 UIActivityIndicatorView)。操作完成後,需要程序化關閉該提示框。

核心方法

UIAlertView 提供了專門的實例方法用於程序化關閉:

- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated;

使用示例

// 顯示加載提示
UIAlertView *loadingAlert = [[UIAlertView alloc] initWithTitle:@"取消預訂" 
                                                       message:@"請稍候..." 
                                                      delegate:self 
                                             cancelButtonTitle:nil 
                                             otherButtonTitles:nil];
[loadingAlert show];

// 添加活動指示器
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] 
    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.center = CGPointMake(loadingAlert.bounds.size.width / 2, 
                               loadingAlert.bounds.size.height - 50);
[indicator startAnimating];
[loadingAlert addSubview:indicator];

// ... 網絡請求完成後關閉提示 ...
[loadingAlert dismissWithClickedButtonIndex:0 animated:YES];

關鍵參數說明

  • buttonIndex:模擬點擊的按鈕索引。無按鈕時傳 0 即可(cancelButtonIndex 通常為 0)。
  • animated:是否啟用關閉動畫,建議傳 YES 提供流暢體驗。

現代替代方案(iOS 7+)

注意:UIAlertView 自 iOS 9 起已棄用,推薦使用 UIAlertController 搭配 UIActivityIndicatorView 實現同樣效果:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"取消預訂" 
                                                               message:@"請稍候..." 
                                                        preferredStyle:UIAlertControllerStyleAlert];

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] 
    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.center = CGPointMake(130.5, 65.5);
[indicator startAnimating];
[alert.view addSubview:indicator];

[self presentViewController:alert animated:YES completion:nil];

// 關閉時
[alert dismissViewControllerAnimated:YES completion:nil];
  1. 上一篇文章:
  2. 下一篇文章:
VB.NET 調用 C++ DLL 結構體中字符數組傳遞漢字導致「數據區域太小」錯誤解決 IcePDF 轉圖片專案中 OOM:單次處理釋放資源 vs 批次處理累積 MGCP 協議軟電話推薦:用於協議分析數據包捕獲 JavaScript 構造函數與原型對象深度解析:prototype、__proto__、constructor 關係全圖譜 jQuery 點擊事件首次無反應:toggle() 替代方案與根因分析 STM32F4DISCOVERY 開發板虛擬串口無法識別?完整解決方案與驅動安裝指南 為何網頁原始碼常見