【iOS8以上版本,苹果推荐使用UIAlertController替代UIAlertView 跟 UIActionSheet】
网上有说以前可以通过-(void)willPresentAlertView:(UIAlertView *)alertView来修改alertView的subview的代码,但是在iOS7以上的系统没有作用。
而且通过-(void)willPresentAlertView:(UIAlertView *)alertView和-(void)didPresentAlertView:(UIAlertView *)alertView获取到的alertView.frame 都是 {{0,0},{0,0}}。
我目前找到两个方法实现UIAlertView内容左对齐:
一个是自定义UIAlertView:
github上正好有一个已经写好的自定义UIAlertView类(CustomIOSAlertView)。
https://github.com/wimagguc/ios-custom-alertview
直接导入CustomIOSAlertView类就可以用了。
#import "CustomIOSAlertView.h"
@interface ViewController ()
@end
@implementation ViewController
//注意,对话框不要创建在viewDidLoad里面,否则不显示,介个折腾了我好久泪!
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self launchDialog];
}
- (void)launchDialog
{
CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
[alertView setContainerView:[self createDemoView]];
[alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消", @"更新", nil]];
[alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
if (buttonIndex == 1) {
NSLog(@"确定");
} else if(buttonIndex == 0){
NSLog(@"取消");
}
[alertView close];
}];
[alertView setUseMotionEffects:true];
[alertView show];
}
- (UIView *)createDemoView
{
float textWidth = 260;
float textMargin = 10;
UILabel *titleLabel = [[UILabel alloc]init];
titleLabel.font = [UIFont systemFontOfSize:18];
titleLabel.textColor = [UIColor blackColor];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.lineBreakMode =NSLineBreakByWordWrapping;
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.text = @"新版本检查";
titleLabel.frame = CGRectMake(0, textMargin, textMargin * 2 + textWidth, 40);
NSString *message = @"1、增加白菜党等特色标签增加白菜党等特色标签增加白菜党等特色标签筛选\n2、增加频道热度排行\n3、增加夜间模式\n4、Material design风格优化\n5、滑动返回优化\n6、其他bug修复";
UIFont *textFont = [UIFont systemFontOfSize:15];
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = textFont;
CGSize maxSize = CGSizeMake(textWidth-textMargin*2, MAXFLOAT);
CGSize size = [message boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(textMargin,CGRectGetMaxY(titleLabel.frame) + textMargin,textWidth, size.height)];
textLabel.font = textFont;
textLabel.textColor = [UIColor blackColor];
textLabel.backgroundColor = [UIColor clearColor];
textLabel.lineBreakMode =NSLineBreakByWordWrapping;
textLabel.numberOfLines =0;
textLabel.textAlignment =NSTextAlignmentLeft;
textLabel.text = message;
UIView *demoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, textWidth + textMargin * 2,CGRectGetMaxY(textLabel.frame)+textMargin)];
[demoView addSubview:titleLabel];
[demoView addSubview:textLabel];
NSLog(@"%@",demoView);
return demoView;
}
第二中针对alertView的方法,由于UIalertView在iOS8中已经不推荐使用,略。