Programmatically change title color of UIButton whose title set as attributed in iOS 7

笑着哭i 提交于 2019-12-21 20:44:57

问题


I have added one UIButton in my UITableView programmatically. My problem is i need to give the Letter Spacing as well as need to change the button title color. I have given the Letter Spacing in button title text using below code, but title text color is not changing.

here is my code :

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];

Can you please help me how to change the button title color here? Thanks.


回答1:


I got answer with help of @Larme.

Only need to add this line :

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

Thanks to all!!




回答2:


Swift Version

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


来源:https://stackoverflow.com/questions/24525224/programmatically-change-title-color-of-uibutton-whose-title-set-as-attributed-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!