原文档:
iOS 自定义UIAlertController的字体、颜色、大小
UIAlertController 代替 UIAlertView 和 UIActionSheet
UIAlertController:新东西就是方便好用,代码量减少,都不用代理了,用起来还更简单了
简单过程:新建 UIAlertController 对其添加 UIAlertAction ,然后 对ViewController 进行 present/dismiss 就可以了。
新版 普通 Alert
// 初始化 添加 提示内容
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"title" message:@"messgae" preferredStyle:UIAlertControllerStyleAlert];
/*
typedef NS_ENUM(NSInteger, UIAlertControllerStyle) {
UIAlertControllerStyleActionSheet = 0,// 不能加输入框,其他一样
UIAlertControllerStyleAlert // 可以添加输入框
} 弹出类型;
*/
// 添加 AlertAction 事件回调(三种类型:默认,取消,警告)
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"ok");
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"cancel");
}];
UIAlertAction *errorAction = [UIAlertAction actionWithTitle:@"error" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"error");
}];
// cancel类自动变成最后一个,警告类推荐放上面
[alertController addAction:errorAction];
[alertController addAction:okAction];
[alertController addAction:cancelAction];
// 出现
[self presentViewController:alertController animated:YES completion:^{
NSLog(@"presented");
}];
// 移除
[alertController dismissViewControllerAnimated:YES completion:^{
NSLog(@"dismiss");
}];
新版 带输入的 Alert
// AlertController 直接添加 textField 即可!
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"name";
}];
// 添加 action,再其回调中可以处理输入内容
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 获取上面的输入框
UITextField *tempField = [alertController.textFields firstObject];
NSLog(@"%@",tempField.text);
NSLog(@"ok");
}];
新版 ActionSheet
// 提示内容 初始化 AlertController
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"title" message:@"messgae" preferredStyle:UIAlertControllerStyleActionSheet];
//其余的完全一致,只是添加 TextField 会报错而已。