Anand Gautam
Anand Gautam

Reputation: 2579

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

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.

Upvotes: 3

Views: 7943

Answers (2)

Abhishek Jain
Abhishek Jain

Reputation: 4739

Swift Version

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

Upvotes: 2

Anand Gautam
Anand Gautam

Reputation: 2579

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!!

Upvotes: 13

Related Questions