iOS – UITableViewCell使文本加粗

我有一个string:

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

我想要做的是大胆的James Johnson和保持@james James Johnson正常的字体。

所以我所尝试的是使用NSAttributedString但是为了完成这个过程,我做了一些错误的事情。

这是我曾经试过的:

 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; 

即使我在错误的方向上,我可以做到这一点吗?

什么不工作

出于某种原因,从0 – 3范围内的字符不是一个轻的字体…而是整个cell.textLabel.text是粗体某种程度上,不是字体大小14,我已经在UIFont中指定。

你的最后一部分是错误的。 您必须创build您的NSAttributedString并最终通过使用垃圾格式

 NSString *str = [string string]; 

由于NSString不知道格式化的任何内容,所以必须使用NSAttributedString将它分配给单元格的textLabel

 cell.textLabel.attributedText = string; 

你应该把attributedString设置为attributed文本

注释这些行

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

并写下这个

 cell.textLabel.attributedText = string;//Set NSMutableAttributedString only not NSString 

UILabel具有属性attributesText。 您应该为您的属性string分配此属性,而不是使用文本属性。

在你的代码中进行更改如下:

  1. 您将需要报告NSMutableAttributedString中的所有字符,因此在添加属性的同时在范围中指定它们。
  2. 提供正确的属性名称,否则你会在这里有一个exception,在这种情况下,你应该使用“NSFontAttribteName”来代替“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;