如果這篇文章幫助到了您,希望您能點(diǎn)擊一下喜歡或者評(píng)論,你們的支持是我前進(jìn)的強(qiáng)大動(dòng)力.謝謝!
從ios8之后,系統(tǒng)的彈框 UIAlertView 與 UIActionSheet 兩個(gè)并在一了起, 使用了一個(gè)新的控制器叫 UIAlertController
下面我就來(lái)介紹以下UIAlertController的簡(jiǎn)單使用
- 1.UIAlertController的創(chuàng)建
/*
參數(shù):
Title:顯示的標(biāo)題
message:標(biāo)題底部顯示的描述信息
preferredStyle:彈框的樣式
樣式分為兩種:UIAlertControllerStyleActionSheet
: UIAlertControllerStyleAlert
*/
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"確定要退出嘛?" message:@“顯示的信息" preferredStyle:UIAlertControllerStyleActionSheet];
- 兩種樣式分別如下
Snip20160302_9.png
- 2.按鈕的創(chuàng)建
- 彈框當(dāng)中的每一個(gè)按鈕分別對(duì)應(yīng)一個(gè) UIAlertAction
- UIAlertAction創(chuàng)建方式如下:
/*
參數(shù):
actionWithTitle:按鈕要顯示的文字
style:按鈕要顯示的樣式
樣式分為三種:
UIAlertActionStyleDefault:默認(rèn)樣式,默認(rèn)按鈕顏色為藍(lán)色
UIAlertActionStyleCancel:設(shè)置按鈕為取消.點(diǎn)擊取消時(shí),會(huì)動(dòng)退出彈框.
注意:取消樣式只能設(shè)置一個(gè),如果有多個(gè)取消樣式,則會(huì)發(fā)生錯(cuò)誤.
UIAlertActionStyleDestructive:危險(xiǎn)操作按鈕,按鈕顏色顯示為紅色
handler:點(diǎn)擊按鈕時(shí)調(diào)用Block內(nèi)部代碼.
*/
UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"點(diǎn)擊了取消");
}];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"點(diǎn)擊了確定");
[self.navigationController popViewControllerAnimated:YES];
}];
- 3.按鈕的添加
//把創(chuàng)建的UIAlertAction添加到控制器當(dāng)中:
[alertController addAction:action];
[alertController addAction:action1];
- 除了添加按鈕之外,還可以添加文本框
- 添加文本框的前提是UIAlertController的樣式必須得要是UIAlertControllerStyleAlert樣式.否則會(huì)直接報(bào)錯(cuò)
- 添加文本框方法為:
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @“文本框點(diǎn)位文字";
}];
- 運(yùn)行效果圖:

- 通過(guò)控制器的textFields屬性獲取添加的文本框.注意textFields它是一個(gè)數(shù)組.
UITextField *textF = alertController.textFields.lastObject;
- 4.顯示彈框.(相當(dāng)于show操作)
[self presentViewController:alertController animated:YES completion:nil];