您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UIAlertController 基本用法完全指南

編輯:iOS 開發綜合

自 iOS 8 起,系統把原本的 UIAlertView 與 UIActionSheet 整合成了一個全新的控制器——UIAlertController。本文帶你快速掌握它的基本用法。

建立 UIAlertController 時有三個參數:
Title:顯示的標題。
message:標題下方的描述資訊。
preferredStyle:彈框樣式,分為兩種——UIAlertControllerStyleActionSheet 與 UIAlertControllerStyleAlert。

第一步:建立控制器

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"確定要退出嘛?"
                                                                       message:@"顯示的信息"
                                                                preferredStyle:UIAlertControllerStyleActionSheet];

第二步:建立按鈕

彈框中的每個按鈕對應一個 UIAlertAction。建立方式如下:
actionWithTitle:按鈕顯示的文字。
style:按鈕樣式,分為三種:
• UIAlertActionStyleDefault:默認樣式,按鈕為藍色。
• UIAlertActionStyleCancel:取消樣式,點擊後退出彈框。注意取消樣式只能設一個,設多個會出錯。
• UIAlertActionStyleDestructive:危險操作按鈕,顯示為紅色。
handler:點擊按鈕時執行的 Block。

UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消"
                                                 style:UIAlertActionStyleCancel
                                               handler:^(UIAlertAction * _Nonnull action) {
    NSLog(@"點擊了取消");
}];

UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"確定"
                                                  style:UIAlertActionStyleDestructive
                                                handler:^(UIAlertAction * _Nonnull action) {
    NSLog(@"點擊了確定");
    [self.navigationController popViewControllerAnimated:YES];
}];

第三步:添加按鈕

[alertController addAction:action];
[alertController addAction:action1];

除了按鈕,還能添加文字輸入框,但前提是樣式必須是 UIAlertControllerStyleAlert,否則會直接報錯:

[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    textField.placeholder = @"文本框點位文字";
}];

透過控制器的 textFields 屬性取得輸入框(注意它是個陣列):

UITextField *textF = alertController.textFields.lastObject;

第四步:顯示彈框

[self presentViewController:alertController animated:YES completion:nil];
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved