iOS -iOS9中提示框(UIAlertController)的常见使用

时间:2023-03-09 18:51:43
iOS -iOS9中提示框(UIAlertController)的常见使用

iOS 8 之前提示框主要使用 UIAlertView和UIActionSheet;iOS 9 将UIAlertView和UIActionSheet合二为一为:UIAlertController 。

这下让已经习惯的我一下子变的不习惯,这样也好,正好再学习一些新的东西;

先上一段代码:

-(void)setupReminder {
//STEP 1
NSString *title = @"提示";
NSString *message = @"请输入用户名和密码";
NSString *okButtonTitle = @"OK"; //step 2 action
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *okCtrl = [UIAlertAction actionWithTitle:okButtonTitle
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action){
}];
//step 3 action
[alertController addAction:okCtrl];
[self presentViewController:alertController animated:YES completion:nil]; }

这是最普通的一个alertcontroller,一个ok按钮。

显示效果:

iOS -iOS9中提示框(UIAlertController)的常见使用

如果UIAlertAction *otherAction这种otherAction >2时,它会自动排列成如下

iOS -iOS9中提示框(UIAlertController)的常见使用

有时需要在alertcontroller中添加一个输入框,例如输入验证码等:

这时候可以添加如下代码:

 

[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {

//you can set textfield attribute here

//add backgroundColor

textField.backgroundColor = [UIColor grayColor];

}];

效果:

iOS -iOS9中提示框(UIAlertController)的常见使用