一、UIAlertController
alert顧名思義是彈出一個提示框,在某個版本以前一直用的是UIAlertView,它繼承的是UIView,現在已經廢棄,但仍可以使用
UIAlertController完全取代了UIAlertView,因爲繼承於UIViewController,理論上功能更強大一點
一般情況下,UIAlertController是點擊某個按鈕後彈出的,我們就可以把UIAlertController的創建寫在某個Button的點擊方法中
在某個button的點擊方法中,我們這樣寫:
1.使用時先初始化,title是顯示的標題,message是標題下面的字,詳細說明,
preferredStyle是樣式有兩種
UIAlertControllerStyleAlert:中間彈出的提示框
UIAlertControllerStyleActionSheet:底部彈出的提示框
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"標題" message:@"這個是UIAlertController的默認樣式" preferredStyle:UIAlertControllerStyleAlert];
2.初始化完畢後警示框是沒有按鈕的,需要單獨添加按鈕UIAlertAction
首先初始化一個按鈕
按鈕的style有三種:
UIAlertActionStyleDefault:默認樣式
UIAlertActionStyleCancel:取消按鈕
UIAlertActionStyleDestructive:紅字的警示按鈕
按鈕的handler屬性後面可以跟一個block,用來傳值
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil];
//把alert窗口用模態方法彈出
[self presentViewController:alertController animated:YES completion:nil];
3.再將按鈕添加到警示框上面去,把警示框用模態的方法添加到父視圖 [alertController addAction:cancel];
[self presentViewController:alertController animated:YES completion:nil];
4.在UIAlertController中我們不但可以添加UIAlertAction按鈕,還可以添加文本框
一般不常用,實現起來一些具體問題也有點繞
先初始化一個UIAlertController,使用addTextFieldWithConfigurationHandler方法添加textField,這個方法後面跟的參數是block,block帶一個UITextField的參數
這個textField就是添加上去的文本框,可以對它的屬性進行設置
UIAlertController *alertController =
[UIAlertController alertControllerWithTitle:@"文本對話框" message:@"登錄和密碼對話框示例" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.text = @"asda";
textField.backgroundColor = [UIColor colorWithRed:109/255.0 green:211/255.0 blue:206/255.0 alpha:1];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.textAlignment = NSTextAlignmentCenter;
}];
這裏可以添加一個方法,對textField上的文字輸入進行限制,少於5字符不能點擊按鈕,
在這個block中聲明一個通知中心,當UITextFieldTextDidChangeNotification發生的時候(也就是textField的內容改變時)
進入方法驗證輸入長度夠不夠
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
//NSNotificationCenter defaultCenter通知一件事的改變會觸發另一個事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
textField.placeholder = @"登錄"; }];
實現一個方法根據textField輸入長度是否夠,控制按鈕是否可點擊
- (void)alertTextFieldDidChange:(NSNotification *)notification{
//得到當前推送的AlertViewController
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
//獲得AlertController上的文本框
UITextField *login = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = login.text.length > 5;
}
}
下面我們展示幾個實例
這是UIAlertControllerStyleAlert類型的,上面添加了一個cancel按鈕和一個destruct按鈕
這是UIAlertControllerStyleActionSheet的樣子
這是添加了文本框的樣子