圖片.png
PS:警告框主要是以警告或提示為目標(biāo)畏腕,最多添加兩個(gè)按鈕缴川,而且除過默認(rèn)類型,每種類型的按鈕只能添加一個(gè)描馅,不然會(huì)崩潰把夸,如果需求更多按鈕,只能選擇操作表铭污。一般的使用場(chǎng)景包括應(yīng)用不能運(yùn)行恋日、詢問另外的解決方案、詢問對(duì)操作的授權(quán)嘹狞。
使用步驟:
<1>創(chuàng)建UIAlertController對(duì)象岂膳,初始化
<2>使用UIAlertAction創(chuàng)建需要的按鈕,并添加到控制器
<3>UIAlertController的方法presentViewController顯示警告框
/**
UIAlertController Demo
*/
- (void)AlertDemo{
//警告框
//UIAlertController 的枚舉成員UIAlertControllerStyleAlert
UIButton *buttonAlert = [[UIButton alloc] initWithFrame:CGRectMake(130, 140, 120, 45)];
buttonAlert.backgroundColor = [UIColor grayColor];
buttonAlert.layer.cornerRadius = 10;
[buttonAlert setTitle:@"警告框" forState:UIControlStateNormal];
[buttonAlert addTarget:self action:@selector(showAlertView:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonAlert];
}
- (void)showAlertView:(id)sender{
NSLog(@"%s", __func__);
//創(chuàng)建初始化
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Alert text goes here!" preferredStyle:UIAlertControllerStyleAlert];
//創(chuàng)建兩個(gè)UIAlertAction(標(biāo)題刁绒,樣式闷营,按鈕動(dòng)作相關(guān)的閉包),最多兩個(gè)(同一個(gè)樣式只能一個(gè),除過默認(rèn)樣式)知市,再多就得使用操作表
UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
NSLog(@"Tap No Button");
}];
UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
NSLog(@"Tap Yes Button");
}];
//添加到控制器
[alertController addAction:noAction];
[alertController addAction:yesAction];
//顯示
[self presentViewController:alertController animated:TRUE completion:nil];
}