Search code examples
iphoneios7uibuttonnsattributedstring

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.


Solution

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