零基础iOS开发学习日记—控件篇—UIAlertController

977 阅读1分钟

开头

UIAlertController

实际用处

  • 输入框
  • 提示框

基本用法

  • 使用UIAlertController要注意两点
  1. 提示框的标题和内容
  2. 提示框下面的按钮UIAlertAction
  3. 使用步骤,创建UIAlertController->创建UIAlertAction->添加UIAlertAction->需要时弹出
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"标题" message:@"内容" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *done = [UIAlertAction actionWithTitle:@"done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    NSLog(@"done");
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    NSLog(@"cancel");
}];
UIAlertAction *destructive = [UIAlertAction actionWithTitle:@"destructive" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"destructive");
}];
[alertController addAction:done];
[alertController addAction:cancel];
[alertController addAction:destructive];
[self presentViewController:alertController animated:YES completion:nil];

UIAlertController样式

  • UIAlertControllerStyleAlert 弹框
  • UIAlertControllerStyleActionSheet 显示在底部

UIAlertAction

  • UIAlertAction共有三种样式
  1. UIAlertActionStyleDefault普通样式,可以添加多个
  2. UIAlertActionStyleCancel加粗样式,一般作为取消,只准添加一个,而且无论添加顺序,都添加在最后一个;如果是只有两个按钮,则添加到最左边
  3. UIAlertActionStyleDestructive红色样式,可以添加多个
  • UIAlertAction具体的实现方法,在创建的回调函数中实现即可

输入框的实现

  • 在基础用法的基础上,调用addTextFieldWithConfigurationHandler即可,添加顺序不影响输入框在按钮上面
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"编辑英雄" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defult = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    NSString *account = alertController.textFields[0].text;
    NSString *password = alertController.textFields[1].text;
    NSLog(@"%@ %@", account, password);
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    textField.placeholder = @"请输入账号";
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    textField.placeholder = @"请输入密码";
    textField.secureTextEntry = YES;
}];
[alertController addAction:defult];
[alertController addAction:cancel];
[self presentViewController:alertController animated:YES completion:nil];