UIAlertView(iOS 9 棄用,現用 UIAlertController)是早期 iOS 應用彈出式提示的核心控件。本文通過「版本更新檢查」實戰場景,講解其創建、代理回調、按鈕索引處理全流程。
- (void)initCheckVersionWithData:(NSData *)data {
NSString *xmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"服務器返回: %@", xmlString);
GetCheckVersion *parser = [[GetCheckVersion alloc] initWithXMLData:data];
[parser parse];
NSString *status = parser.tempResult.status; // "200"=有更新, "201"=無更新
NSLog(@"版本狀態: %@", status);
if ([@"201" isEqualToString:status]) {
NSLog(@"已是最新版本");
} else if ([@"200" isEqualToString:status]) {
[self showUpdateAlert];
}
}
- (void)showUpdateAlert {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"發現新版本"
message:@"是否立即更新?"
delegate:self
cancelButtonTitle:@"稍後更新"
otherButtonTitles:@"立即更新", nil];
// 可選:添加更多按鈕
// [alert addButtonWithTitle:@"查看詳情"];
[alert show];
// ARC 環境下無需手動 release
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(@"用戶點擊了按鈕索引: %ld", (long)buttonIndex);
if (buttonIndex == 0) { // 取消按鈕 (cancelButtonTitle)
NSLog(@"用戶選擇稍後更新");
return;
} else if (buttonIndex == 1) { // 第一個 otherButtonTitles
NSLog(@"用戶確認更新,啟動下載");
[self.httpClient getUpdateVersion]; // 觸發下載/跳轉 App Store
}
// 如果有更多按鈕:buttonIndex 2, 3...
}
| 屬性/方法 | 說明 |
|---|---|
title | 標題文本(粗體顯示) |
message | 正文文本(多行自動換行) |
delegate | 遵循 UIAlertViewDelegate 的對象 |
cancelButtonIndex | 取消按鈕索引(默認 0) |
numberOfButtons | 按鈕總數 |
buttonTitleAtIndex: | 獲取指定索引按鈕標題 |
show | 彈出顯示(模態,阻塞當前 RunLoop) |
dismissWithClickedButtonIndex:animated: | 程序化關閉 |
- (void)showUpdateAlertModern {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"發現新版本"
message:@"是否立即更新?"
preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"稍後更新"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action) {
NSLog(@"稍後更新");
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"立即更新"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[self.httpClient getUpdateVersion];
}]];
[self presentViewController:alert animated:YES completion:nil];
}
UIAlertActionStyleDestructive(紅色字體)。從 UIAlertView 到 UIAlertController,是 iOS 交互 API 現代化的縮影。