【问题标题】:Programmatically change title color of UIButton whose title set as attributed in iOS 7以编程方式更改 UIButton 的标题颜色,其标题设置为 iOS 7 中的属性
【发布时间】:2014-08-22 21:30:50
【问题描述】:

我以编程方式在我的UITableView 中添加了一个UIButton。我的问题是我需要提供Letter Spacing 以及需要更改按钮标题颜色。我使用下面的代码在按钮标题文本中给出了Letter Spacing,但标题文本颜色没有改变。

这是我的代码:

btnLogin = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnLogin.frame = CGRectMake(0, 0, 320, 42);
btnLogin.titleLabel.font = customFont;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"LOG IN"];

[attributedString addAttribute:NSKernAttributeName
                         value:@(spacing)
                         range:NSMakeRange(0, [@"LOG IN" length])];

[btnLogin setAttributedTitle:attributedString forState:UIControlStateNormal];

btnLogin.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"cell_highlighted.png"]];

[btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; //it's not working.

[btnLogin addTarget:self action:@selector(onClickLogin) forControlEvents:UIControlEventTouchUpInside];

[cell addSubview:btnLogin];
[cell.contentView bringSubviewToFront:btnLogin];

您能帮我在这里更改按钮标题颜色吗?谢谢。

【问题讨论】:

  • 添加这一行:[attributedString addAttribute:NSForegroundAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, [@"LOG IN" length])];
  • 哇太棒了..它的工作。只需将 NSForegroundAttributeName 改为 NSForegroundColorAttributeName。非常感谢@Larme
  • 我的错,忘记了名称属性中的“颜色”。嗯,原因是因为attributedTitle 是一个“新”属性,而titleColor 适用于UIButtontitle 属性,不适用于attributedTitle

标签: iphone ios7 uibutton nsattributedstring


【解决方案1】:

我在@Larme 的帮助下得到了答案。

只需要添加这一行:

[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, [@"LOG IN" length])];

谢谢大家!!

【讨论】:

  • 你可以使用AttributeString.length,而不是从字符串中获取长度,比如:NSMakeRange(0, attributesString.length)
【解决方案2】:

Swift 版本

 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.skyBlue, range: NSMakeRange(0, attributedString.string.length))

【讨论】:

    猜你喜欢
    • 2012-09-21
    • 2014-11-07
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2015-11-25
    • 2011-01-29
    相关资源
    最近更新 更多