一通贞、基本使用
使用UIAlertController 需三步:
1.創(chuàng)建控制器并指定樣式和參數(shù).。
2.添加按鈕addAction。
3.模態(tài)推出(底部或中間彈出)敬飒。
// 1\. 創(chuàng)建alert控制器并指定style:UIAlertControllerStyleAlert||UIAlertControllerStyleActionSheet 本文以 Alert為例展示
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"確定要操作?" message:@"操作后不可恢復(fù)" preferredStyle:UIAlertControllerStyleAlert];
// 2. 添加選項(xiàng)
[alertController addAction: [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
NSLog(@"點(diǎn)擊了取消");
}]];
[alertController addAction: [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSLog(@"點(diǎn)擊了確定");
}]];
// 3. 模態(tài)退出控制器
[self presentViewController:alertController animated:YES completion:nil];
*如果選項(xiàng)添加超過兩個(gè),會(huì)豎向排列芬位。
![image](http://upload-images.jianshu.io/upload_images/9374943-ab05683d5b38174a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
二无拗、可添加輸入框,可用作輸入密碼等功能昧碉,也可添加多個(gè)輸入框(如用戶名和密碼)英染。
效果圖:
*要對(duì)輸入框中的文字進(jìn)行監(jiān)測(cè),密碼超過6位確定按鈕才可點(diǎn)被饿。
因?yàn)橐獙?duì)AlertController的成員進(jìn)行監(jiān)聽四康,并且操作確定按鈕,所以提兩個(gè)全局變量狭握。
UIAlertAction * _otherAction; //確定按鈕
UIAlertController * _alertController; // 控制器
-(void)buttonClinck{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"輸入密碼" message:@"密碼為開機(jī)密碼" preferredStyle:UIAlertControllerStyleAlert];
_alertController = alertController;
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.secureTextEntry = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
}];
__weak actionsheetController *Wself = self;
//blcok中使用self最好用copy弱指針self闪金,雖然有些block是局部變量(self并不包含block),但為保險(xiǎn)论颅,告誡自己都用毕泌。
[alertController addAction: [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[Wself remoteNotif];
}]];
UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[Wself remoteNotif];
}];
[alertController addAction: otherAction];
otherAction.enabled = NO;
_otherAction = otherAction;
//先將確定按鈕設(shè)為不可點(diǎn)喝检,在通知中當(dāng)輸入的密碼大于n位數(shù)可以點(diǎn)
//推出控制器
[self presentViewController:alertController animated:YES completion:nil];
}
-(void)remoteNotif{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:_alertController.textFields.firstObject];
}
-(void)handleTextFieldTextDidChangeNotification:(NSNotification *)notification{
UITextField *textFile = notification.object;
_otherAction.enabled = textFile.text.length>5?YES:NO;
}
至此完結(jié),注意添加監(jiān)聽后要移除撼泛。
文章借鑒網(wǎng)絡(luò)挠说,怕忘了自己總結(jié)的。不對(duì)的地方愿题,請(qǐng)?zhí)岢觥?/p>