iOS - UITableViewCell make text bold

2019-06-22 01:16发布

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.

4条回答
Melony?
2楼-- · 2019-06-22 01:51

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;
查看更多
男人必须洒脱
3楼-- · 2019-06-22 01:54

Make changes in you code as follows :

  1. You will require to report all the characters with in the NSMutableAttributedString, so specify them with in the range, while adding an attribute.
  2. Provide correct attribute name, else you will have an exception here, in this case you should use "NSFontAttribteName" in place of "NSForegroundColorAttributeName".
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:user];

[string addAttribute:NSFontAttributeName value:fontLight range:NSMakeRange(0, 20)];

[string addAttribute:NSFontAttributeName value:fontBold range:NSMakeRange(0, 5)];


cell.textLabel.attributedText = string;
查看更多
混吃等死
4楼-- · 2019-06-22 02:02

UILabel has a property attributedText. You should be assigning this property with your attributed string and not use text property.

查看更多
神经病院院长
5楼-- · 2019-06-22 02:09

You should set attributedString to attributed text

Comment these lines

//NSString *str = [string string];
//cell.textLabel.text = str;

And write this

cell.textLabel.attributedText = string;//Set NSMutableAttributedString only not NSString
查看更多
登录 后发表回答