如何更改UIAlertView文本颜色?

时间:2011-01-21 04:16:05

标签: iphone cocoa-touch uikit uialertview

我目前正在使用http://kwigbo.com/post/318396305/iphone-sdk-custom-uialertview-background-color作为我的自定义UIAlertView。一切正常,但我正在尝试更改标题和消息文本颜色,我想更改按钮颜色。有没有办法做到这一点?我尝试过使用:

UILabel *theTitle = [AlertView valueForKey:@"_titleLabel"];
    [theTitle setTextColor:[UIColor redColor]];

但我无法让它发挥作用。任何帮助,将不胜感激。感谢。

3 个答案:

答案 0 :(得分:1)

您只需在UIAlertViewDelegate文件中加入.h,并在.m文件中覆盖此方法。

-(void)willPresentAlertView:(UIAlertView *)alertView{
    UILabel *theTitle = [alertView valueForKey:@"_titleLabel"];
    theTitle.font = [UIFont fontWithName:@"Copperplate" size:18];
    [theTitle setTextColor:[UIColor whiteColor]];

    UILabel *theBody = [alertView valueForKey:@"_bodyTextLabel"];
    theBody.font = [UIFont fontWithName:@"Copperplate" size:15];
    [theBody setTextColor:[UIColor whiteColor]];
}

答案 1 :(得分:0)

检查setTextColor是否已被删除。

我以为是

theTitle.text.color = [UIColor redColor];

或者您可以使用

[theTitle.text setColor:[UIColor redColor]];

第二个不完全肯定,第一个例子应该可以做到这一点。

答案 2 :(得分:0)

默认情况下,您无法更改警报视图标题和消息,但借助附件视图,您可以实现此功能。 尝试以下方法:

-(void)customAlertTitle:(NSString*)title message:(NSString*)message{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:nil cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];

UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 270, 50)];
titleLabel.text = title;
titleLabel.font = [UIFont boldSystemFontOfSize:20];
titleLabel.numberOfLines = 2;
titleLabel.textColor = [UIColor redColor];
titleLabel.textAlignment = NSTextAlignmentCenter;

[subView addSubview:titleLabel];

UILabel *messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, 270, 50)];
messageLabel.text = message;
messageLabel.font = [UIFont systemFontOfSize:18];
messageLabel.numberOfLines = 2;
messageLabel.textColor = [UIColor redColor];
messageLabel.textAlignment = NSTextAlignmentCenter;

[subView addSubview:messageLabel];

[alertView setValue:subView forKey:@"accessoryView"];
[alertView show];
}

以上代码在最新的XCode 8.3.1上运行良好。如果遇到任何问题,请发表评论。

相关问题