Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - UITableViewCell make text bold

I have a string:

NSString *userInfo = @"James Johnson @james";

What i want to do is bold James Johnson and keep @james normal font.

So what I have tried is using NSAttributedString but somewhere I'm doing something wrong in order to complete the process.

This is what I have tried:

NSString *user = @"James Johnson @james";

UIFont *fontLight = [UIFont fontWithName:@"HelveticaNeue-Light" size:14];
UIFont *fontBold = [UIFont fontWithName:@"HelveticaNeue-Bold" size:14];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:userInfo];

//TESTING WITH RANDOM PARTS OF THE STRIN
[string addAttribute:NSForegroundColorAttributeName value:fontLight range:NSMakeRange(0, 3)];
[string addAttribute:NSForegroundColorAttributeName value:fontBold range:NSMakeRange(3, 5)]; 

NSString *str = [string string];

cell.textLabel.text = str;

Is there a way I can make this work even if I'm on the wrong direction?

What's not working

For some reason, the characters from range 0 - 3 is not being a light font...instead the entire cell.textLabel.text is bold somehow and is not font size 14 which i had specified in the UIFont.

like image 853
Vanessa Avatar asked Dec 31 '13 07:12

Vanessa


1 Answers

Your last part of it is wrong. You must create your NSAttributedString and finally trash the formatting by using

NSString *str = [string string];

As NSString doesn't know anything about formatting you have to use the NSAttributedString to assign it to the cell's textLabel:

cell.textLabel.attributedText = string;
like image 132
Florian Mielke Avatar answered Sep 23 '22 07:09

Florian Mielke