Programmatically change the color of the UIButton header, the name of which is specified in iOS 7

I added one UIButton to my UITableView programmatically. My problem is that I need to give Letter Spacing and also change the color of the button name. I gave the Letter Spacing text in the button title using the code below, but the color of the title text does not change.

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 not working. [btnLogin addTarget:self action:@selector(onClickLogin) forControlEvents:UIControlEventTouchUpInside]; [cell addSubview:btnLogin]; [cell.contentView bringSubviewToFront:btnLogin]; 

Could you help me change the color of the button name here? Thank.

+1
iphone ios7 uibutton nsattributedstring
Jul 02 '14 at 7:26
source share
3 answers

I got a response using @Larme.

You just need to add this line:

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

Thanks everyone!

+10
Jul 02 '14 at 8:16
source share

Quick version

  attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.skyBlue, range: NSMakeRange(0, attributedString.string.length)) 
0
09 Oct '17 at 15:46 on
source share

Swift 4 version (built on Abhishek answer ):

 attString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.white, range: NSMakeRange(0, attString.string.count)) 
-one
Dec 17 '17 at 1:05
source share



All Articles