引言:
UIAlertController的基本使用
一个简单的提示框:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"标题" message:@"正文" preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
// 点击确定按钮时 要进行的操作可以写到这里
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
// 点击取消按钮时 要进行的操作可以写到这里
}];
[alert addAction:cancelAction];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
自定义UIAlertController
主要是使用kvc的方式来自定义UIAlertController的样式:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"标题" message:@"内容" preferredStyle:UIAlertControllerStyleAlert];
// 使用富文本来改变alert的title字体大小和颜色
NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:@"这里是标题"];
[titleText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:24] range:NSMakeRange(0, 2)];
[titleText addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
[alert setValue:titleText forKey:@"attributedTitle"];
// 使用富文本来改变alert的message字体大小和颜色
// NSMakeRange(0, 2) 代表:从0位置开始 两个字符
NSMutableAttributedString *messageText = [[NSMutableAttributedString alloc] initWithString:@"这里是正文信息"];
[messageText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, 6)];
[messageText addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
[messageText addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:NSMakeRange(3, 3)];
[alert setValue:messageText forKey:@"attributedMessage"];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
// 设置按钮背景图片
UIImage *accessoryImage = [[UIImage imageNamed:@"selectRDImag.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[cancelAction setValue:accessoryImage forKey:@"image"];
// 设置按钮的title颜色
[cancelAction setValue:[UIColor lightGrayColor] forKey:@"titleTextColor"];
// 设置按钮的title的对齐方式
[cancelAction setValue:[NSNumber numberWithInteger:NSTextAlignmentLeft] forKey:@"titleTextAlignment"];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:okAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
效果图:
效果图
demo下载地址:CustomAlertControllerDemo
原文链接:http://www.jianshu.com/p/a0785cb0601b