2015-11-12 42 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

相關問題