ios8之后的UIAlertController整合了之前的UIAlertView与UIActionSheet,使用回调的handler代替了繁琐的delegate,对外接口极其简单易用。但另一方面,一些UIAlertView与UIActionSheet允许使用的官方不鼓励的自定义方法在ios8中是不支持的。UIAlertController的封装相当严谨。
目前已经知道通过遍历subview来改变actionsheet的按钮样式ios8不支持,直接改变alertController的view.tintColor会导致actionsheet的布局改变。
UIAlertController的主要方法
//初始化
- (id)alertControllerWithTitle:(NSString *)title message:(NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle
preferredStyle决定是创建actionsheet还是alertview的样式
//为按钮添加动作
- (void)addAction:(UIAlertAction *)action
ios8以后对按钮的样式和动作进行了抽象。UIAlertAction的创建使用
- (id)actionWithTitle:(NSString *)title
style:(UIAlertActionStyle)style
handler:(void (^)(UIAlertAction *action))handler
title是按钮文字
style决定是一般按钮、默认的取消按钮或者要标红的按钮
handler是一个block,按钮接受点击后执行。我在封装兼容之前版本alertview和Actionsheet的Controller时,对外统一用UIAlertController的接口。在新的Controller中实现UIActionSheetDelegate和UIAlertViewDelegate,执行传递的handler。以actionsheet为例:
#pragma mark actionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
NEWAlertAction *action = [[NEWAlertAction alloc] init];
NEWHandler handle = _handlers[buttonIndex];
if (handle) {
handle(action);
}
}
_handlers保存了对应index button的回调函数。
下面是新旧两个版本改变按钮文字颜色的方法,其他修改类似:
//支持alertController的版本
[[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:UIColorBlack];
//旧版本
#pragma mark actionSheetDelegate
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet{
for(UIView * view in actionSheet.subviews){
if ([view isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton*)view;
[button setTitleColor:UIColorBlack forState:UIControlStateNormal];
}
}
}