Android 的 AlertDialog 支持設置單選/多選列表項,iOS 原生 UIAlertController (iOS 8+) 僅支援簡單的 Action 按鈕,**不直接支援帶複選框/單選框的列表內容**。需自定義視圖控制器實現。
創建一個繼承 UIViewController 的自定義類,在 XIB/Storyboard 中設計包含表格/列表的界面,以 Modal 方式呈現。
// MyCustomAlertViewController.h
@interface MyCustomAlertViewController : UIViewController
@property (nonatomic, copy) NSString *agentName;
@property (nonatomic, copy) NSString *agentPhoneNumber;
// 可添加更多數據屬性
@end
- (void)showCustomAlertWithAgentName:(NSString *)name phoneNumber:(NSString *)phone {
// 1. 實例化自定義 VC (從 XIB 或 Storyboard)
MyCustomAlertViewController *modalVC = [[MyCustomAlertViewController alloc]
initWithNibName:@"MyCustomAlertViewController" bundle:nil];
modalVC.agentName = name;
modalVC.agentPhoneNumber = phone;
// 2. 嵌入導航控制器 (可選,提供導航欄、標題、關閉按鈕)
UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:modalVC];
navVC.modalPresentationStyle = UIModalPresentationFormSheet; // iPad 上顯示為表單頁
// 3. 呈現
[self presentViewController:navVC animated:YES completion:nil];
}
- (IBAction)dismissButtonTapped:(id)sender {
[self.dismissViewControllerAnimated:YES completion:nil];
// 或 [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
封裝一個可復用的 OptionAlertController:
@interface OptionAlertController : UIViewController
@property (nonatomic, strong) NSArray *options; // 選項數組
@property (nonatomic, copy) void (^onSelect)(NSInteger index, NSString *option);
+ (instancetype)alertWithTitle:(NSString *)title options:(NSArray *)options onSelect:(void (^)(NSInteger, NSString *))handler;
@end
// 使用
[OptionAlertController alertWithTitle:@"選擇操作"
options:@[@"編輯", @"刪除", @"分享", @"取消"]
onSelect:^(NSInteger index, NSString *option) {
if (index == 0) { /* 編輯 */ }
else if (index == 1) { /* 刪除 */ }
}].showInViewController(self);
內部實現可基於 UITableView 或 UICollectionView,支援單選、多選、自定義 Cell、圖標、分組等豐富交互。
| 庫 | 特點 | 支援列表選項 |
|---|---|---|
| ActionSheetPicker-3.0 | 經典選擇器,支援字符串、日期、自定義 | ✅ |
| SCLAlertView | 漂亮動畫、自定義內容視圖 | ✅ (嵌入 TableView) |
| PMAlertController | 可自定義 Cell、圖標、顏色 | ✅ |
| AlertController (Swift) | 類似 UIAlertController API,支援 TextField、Picker | ✅ |
iOS 無原生「帶選項列表的 Alert」,標準做法是**自定義 UIViewController + Modal 呈現**,或接入成熟第三方庫。自定義方案靈活性最高,可完美還原 Android 風格甚至超越。