以编程方式更改UIButton的标题颜色,其标题设置为iOS 7中的属性

问题描述 投票:3回答:2

我以编程方式在UIButton中添加了一个UITableView。我的问题是我需要给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];

你能帮我解决一下如何更改按钮标题颜色吗?谢谢。

iphone ios7 uibutton nsattributedstring
2个回答
11
投票

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

只需添加此行:

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

谢谢大家!!


2
投票

Swift版本

 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.skyBlue, range: NSMakeRange(0, attributedString.string.length))
© www.soinside.com 2019 - 2024. All rights reserved.