显示具有多种格式的单词的字符串

Display string having words with multiple formatting

在我的应用程序中,我正在显示从服务器获取的用户评论。评论包含用户名、标签和一些粗体文字。

例如:Nancy 已标记 Clothing: 第 2 季第 5 集。 他们在哪里可以找到所有旧衣服

单词"Nancy"和"Clothing:"应该分别是灰色和橙色,"Season 2, Episode 5."应该是粗体。

我已经尝试使用 NSAttributedString 但未能实现上述目标。

以下是我尝试更改颜色但没有任何改变的代码。我不太确定如何使用 NSAttributedString。

NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:", tag.title]];
    [title addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:246/255.0 green:139/255.0 blue:5/255.0 alpha:1.0f] range:NSMakeRange(0,[title length])];
    self.tagCommentLabel.text = [NSString stringWithFormat:@"%@ tagged %@: %@ %@",tag.user.name , title, episode, tag.comment];

谁能帮我写一段代码,告诉我怎样才能用所需的格式实现例句?

您将不得不添加逻辑,因为我很确定您不想 总是 color/bold 这个特定的词,但在这里您可以快速示例:

NSString *title = @"Nancy tagged Clothing: Season 2, Episode 5. where do they find all the old clothes";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title];

// Color text for range of string
[attributedString addAttribute:NSForegroundColorAttributeName
                         value:[UIColor grayColor]
                         range:[title rangeOfString:@"Nancy"]];
[attributedString addAttribute:NSForegroundColorAttributeName
                         value:[UIColor grayColor]
                         range:[title rangeOfString:@"Clothing"]];

// Bold (be careful, I have used system font with bold and 14.0 size, change the values as for yourself)
[attributedString addAttribute:NSFontAttributeName
                         value:[UIFont systemFontOfSize:14.0 weight:UIFontWeightBold]
                         range:[title rangeOfString:@"Season 2"]];
[attributedString addAttribute:NSFontAttributeName
                         value:[UIFont systemFontOfSize:14.0 weight:UIFontWeightBold]
                         range:[title rangeOfString:@"Season 5"]];

self.tagCommentLabel.attributesText = attributedString;

编辑: 要使其适用于您的代码,请删除以下行:

self.tagCommentLabel.text = [NSString stringWithFormat:@"%@ tagged %@: %@ %@",tag.user.name , title, episode, tag.comment];

不是我用静态文本分配给标题,而是将其更改为:

NSString *title = [NSString stringWithFormat:@"%@ tagged %@: %@ %@",tag.user.name , title, episode, tag.comment];

NSAttributedString 和 NSString 是两个不同的东西。如果你想给 NSString 添加属性(例如改变文本的颜色),你必须首先使 NSString:

NSString *string = [NSString stringWithFormat:@"%@ tagged %@: %@ %@",tag.user.name , title, episode, tag.comment];

然后你从你的 NSString 生成 NSMutableAttributedString 并向它添加属性:

NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string]; 
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:246/255.0 green:139/255.0 blue:5/255.0 alpha:1.0f] range:[string rangeOfString:title];

当你想显示你的属性字符串时,你应该使用 .attributedText 而不是 .text:

self.tagCommentLabel.attributedText = attString;