ios警告框

ios警告框_第1张图片
图片.png

PS:警告框主要是以警告或提示为目标,最多添加两个按钮,而且除过默认类型,每种类型的按钮只能添加一个,不然会崩溃,如果需求更多按钮,只能选择操作表。一般的使用场景包括应用不能运行、询问另外的解决方案、询问对操作的授权。
使用步骤:
<1>创建UIAlertController对象,初始化
<2>使用UIAlertAction创建需要的按钮,并添加到控制器
<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__);
    
    //创建初始化
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Alert text goes here!" preferredStyle:UIAlertControllerStyleAlert];
    
    //创建两个UIAlertAction(标题,样式,按钮动作相关的闭包),最多两个(同一个样式只能一个,除过默认样式),再多就得使用操作表
    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];

}

你可能感兴趣的:(ios警告框)