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

iOS 實現類似 Android 帶選項列表的警報對話框

     編輯:程式設計綜合問答

需求背景

Android 的 AlertDialog 支持設置單選/多選列表項,iOS 原生 UIAlertController (iOS 8+) 僅支援簡單的 Action 按鈕,**不直接支援帶複選框/單選框的列表內容**。需自定義視圖控制器實現。

方案:自定義 Modal ViewController

創建一個繼承 UIViewController 的自定義類,在 XIB/Storyboard 中設計包含表格/列表的界面,以 Modal 方式呈現。

1. 自定義控制器

// MyCustomAlertViewController.h
@interface MyCustomAlertViewController : UIViewController
@property (nonatomic, copy) NSString *agentName;
@property (nonatomic, copy) NSString *agentPhoneNumber;
// 可添加更多數據屬性
@end

2. 彈出邏輯

- (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];
}

3. 關閉邏輯 (在自定義 VC 內部)

- (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 風格甚至超越。

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