自定义AlertController
iOS8之后,系统给我们提供了UIAletController这个类用来做用户提示,使用方法很简单,有两种枚举类型可以选择,alert和sheet样式,这iOS8之前方式差不多,只是将代理的方式改成了block,这样代码上看起来就更直观。但是,系统提供的类往往并不能满足我们的需求,有时候需要修改文字的颜色等等,所以我们来看看UIAletController中到底是什么样的?
1.获取UIAlertAction中的所有属性(通过运行时获取)
Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = *(ivars + i);
NSLog(@"变量名======");
NSLog(@"%s", ivar_getName(ivar));
NSLog(@"变量类型======");
NSLog(@"%s", ivar_getTypeEncoding(ivar));
}
获取到UIAlertAction的实例变量为
==变量名====== _title
变量类型====== @”NSString”
变量名====== _titleTextAlignment
变量类型====== q
变量名====== _enabled
变量类型====== B
变量名======_checked
变量类型======B
变量名======_isPreferred
变量类型======B
变量名======_imageTintColor
变量类型======@”UIColor”
变量名======_titleTextColor
变量类型======@”UIColor”
变量名======_style
变量类型======q
变量名======_handler
变量类型======@?
变量名======_simpleHandler
变量类型======@?
变量名======_image
变量类型======@”UIImage”
变量名====== _shouldDismissHandler
变量类型====== @?
变量名======__descriptiveText
变量类型======@”NSString”
变量名====== _contentViewController
变量类型====== @”UIViewController”
变量名======_keyCommandInput
变量类型======@”NSString”
变量名======_keyCommandModifierFlags
变量类型======q
变量名======__representer
变量类型====== @””
变量名====== __interfaceActionRepresentation
变量类型======@”UIInterfaceAction”
变量名======__alertController
变量类型====== @”UIAlertController”==
从中可以找到这样的几个有用的属性,当然,如果你有兴趣,也可以试试其他的属性,同样的,title和message也可以通过遍历UIAletController获得
//自定义title和message
NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:title];
[alertControllerStr addAttribute:NSForegroundColorAttributeName value:textColor range:NSMakeRange(0, title.length)];
[alertControllerStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@".PingFangSC-Regular" size:fontSize] range:NSMakeRange(0, title.length)];
[self setValue:alertControllerStr forKey:@"attributedTitle"];
}
- (void)messageStyleWithMessage:(NSString *)message FontSize:(CGFloat)fontSize messageColor:(UIColor *)messageColor {
NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:message];
[alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:messageColor range:NSMakeRange(0, message.length)];
[alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@".PingFangSC-Regular" size:fontSize] range:NSMakeRange(0, message.length)];
[self setValue:alertControllerMessageStr forKey:@"attributedMessage"];
}
_titleTextAlignment
_titleTextColor
_image
但是并没有找个可以改变字体样式的属性,通过修改_titleTextColor
和_image
可以得到这样的样式
如果仅仅是修改文字的颜色的话,这样做就已经足够了;
2.在项目中,我们可能会修改文字的font,所以看看UIAlertController在显示的时候的图层
这里写图片描述
当我在寻找的时候,并没有找到最底层的action,在这个过程中,找到UIStackView的时候,就无法获取其中的子视图了,这可能是苹果做了什么特殊的处理。
3.最后因为项目时间紧,所以通过自定义的方式实现了需求
最后通过storyboard中的containerView实现了可以自定义的效果;注意,要做屏幕适配(自动调整)的时候,需要设置以下方法
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
代码详见XEL_AlertController