提示框message左对齐问题

来源:互联网 发布:linux ftp命令 编辑:程序博客网 时间:2024/06/05 20:38

前言

今天需要改一个将提示框中message左对齐的需求,而苹果SDK中并没有公开一些属性来设置其中message的样式。所以其实只有拿到用来展示message的那个控件就好了,然后设置它的一些属性,其实就是label。查了一些资料,特此整理一下

正文

从iOS8过后苹果建议使用UIAlertController替代UIAlertView,所以就有两种情况

UIAlertView

适用于iOS7以及iOS7以下的版本,想必过不了多久也就没人用iOS7了吧。可以直接在其代理方法-(void)willPresentAlertView:(UIAlertView *)alertView中实现以下方法就可:

- (void)willPresentAlertView:(UIAlertView *)alertView{        for( UIView * view in alertView.subviews )        {            if( [view isKindOfClass:[UILabel class]] )            {                UILabel* label = (UILabel*) view;                label.textAlignment = UITextAlignmentLeft;            }        }}

拿到alertView,遍历它的子视图,找到UILabel那个控件,然后将其文字样式设置为左对齐。
其实UILable在alertView.subviews里面是第3个元素,第一个元素是一个UIImageView(背景),UILable(标题),UILable(Message),UIButton(Cancel)…(如果还有的话以此类推)

UIAlertController

由于UILabel在UIAlertController的View中的层级比较深,所以可以通过遍历来找到UILabel(其实需要遍历6次才能找到),代码如下:

{UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:alertControllerStyle];    UIView *messageParentView = [self getParentViewOfTitleAndMessageFromView:alertController.view];    if (messageParentView && messageParentView.subviews.count > 1) {        UILabel *messageLb = messageParentView.subviews[1];        messageLb.textAlignment = NSTextAlignmentLeft;    }}- (UIView *)getParentViewOfTitleAndMessageFromView:(UIView *)view {    for (UIView *subView in view.subviews) {        if ([subView isKindOfClass:[UILabel class]]) {            return view;        }else{            UIView *resultV = [self getParentViewOfTitleAndMessageFromView:subView];            if (resultV) return resultV;        }    }    return nil;} 

结语

遇到问题还是要多思考,就算苹果没有直接的方法去实现也不要慌张,总能找到解决之道。
如果只是修改左对齐,采用系统的,用上面的方法即可。如果还有一些复杂的用法,在UIAlertView上添加自己写的UILabel,设置其左对齐,或者其他控件,可用在GitHub上面有1430个star之多的第三方CustomIOSAlertView也非常方便。

0 0