一、就一個選項的對話框
代碼塊
#pragma mark - 封裝彈出對話框方法 // 提示錯誤信息 - (void)showError:(NSString *)errorMsg { // 1.彈框提醒 // 初始化對話框 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:errorMsg preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil]]; // 彈出對話框 [self presentViewController:alert animated:true completion:nil]; }
需要調用彈出對話框方法的地方使用的代碼如下:
代碼塊
// 彈出“請檢查用戶名和密碼是否為空!”對話框 [self showError:@"請檢查用戶名和密碼是否為空!"];
效果如圖所示:
二、如果是要做兩個選項的對話框
先在.h文件中定義如下:
@property (strong, nonatomic) UIAlertAction *okAction; @property (strong, nonatomic) UIAlertAction *cancelAction;
然后在.m文件中寫入如下代碼:
#pragma mark - 注銷:彈出對話框 - (void) logout { // 初始化對話框 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"確認注銷嗎?" preferredStyle:UIAlertControllerStyleAlert]; // 確定注銷 _okAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) { // 1.清除用戶名、密碼的存儲 // 2.跳轉到登錄界面 [self performSegueWithIdentifier:@"Logout" sender:nil]; }]; _cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; [alert addAction:_okAction]; [alert addAction:_cancelAction]; // 彈出對話框 [self presentViewController:alert animated:true completion:nil]; }
需要調用彈出對話框方法的地方使用的代碼如下:
代碼塊
// 彈出“確認注銷嗎?”對話框 [self logout];
效果如圖所示: