2015-11-12 29 views
1

当我使用UIAlertView时,我发现消息的textAligment是Center。例如,当我写这篇文章的代码:如何在UIAlertView中更改消息的对齐方式?

UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil 
                message:@"this is first line  \nsecondLine should be center" 
                delegate:nil 
             cancelButtonTitle:nil 
             otherButtonTitles:nil, nil]; 
[alertView show]; 

效果如下:enter image description here
正如我们看到的,文本“这是第一行”是在中央,但我想将其更改为left.I知道UILabel可以改变文本的对齐方式,但我不知道是否可以在UIAlertView中进行更改。

回答

1

iOS7:对于左对齐,你可以这样做:

NSArray *subViewArray = alertView.subviews; 
for(int x = 0; x < [subViewArray count]; x++){ 

    //If the current subview is a UILabel... 
    if([[[subViewArray objectAtIndex:x] class] isSubclassOfClass:[UILabel class]]) { 
     UILabel *label = [subViewArray objectAtIndex:x]; 
     label.textAlignment = NSTextAlignmentLeft; 
    } 
} 

编号:How to make a multiple line, left-aligned UIAlertView?

或者你也可以一个的UILabel添加到alertView:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Centered Title" message:@"\n\n\n" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil]; 

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12.0, 24.0, 250.0, 80.0)]; 
    label.numberOfLines = 0; 
    label.textAlignment = NSTextAlignmentLeft; 
    label.backgroundColor = [UIColor clearColor]; 
    label.textColor = [UIColor whiteColor]; 
    label.text = @"Here is an example of a left aligned label in a UIAlertView!"; 
    [alert addSubview:label]; 
    [alert show]; 

编号:How to align only the title in UIAlertView

+1

我尝试使用此解决方案。但我发现subViewArray中没有任何对象。 – huixing

+0

@huixing是的,它只适用于iOS <= 7.我编辑了我的答案。 – anhtu

2

像这样编辑你的代码。

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil 
               message:nil 
               delegate:nil 
            cancelButtonTitle:nil 
            otherButtonTitles:nil, nil]; 


UILabel *v = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 40)]; 
v.text = NSTextAlignmentLeft; 
v.numberOfLines = 0; 
v.text = @"this is first line\nsecondLine should be center"; 
[alert setValue:v forKey:@"accessoryView"]; 
[alert show]; 
+0

是的,它工作。但我想知道关键“accessoryView”。有没有文件提到它?另外,设置标签“v”的框架不起作用。 – huixing

+0

但它在NSAlert中起作用,这在mac开发中很有用。 UIAlertView是否一样? – huixing

+0

“accessoryView”是私人的。所以,这可能会被你的应用拒绝。所以,我建议你到UIAlertViewController /自定义你的警报。 – Jamil