UIAlertController初探

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];
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值