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

时间:2015-11-02 20:58:01

标签: ios objective-c nsattributedstring

在我的应用中,我正在显示从服务器获取的用户评论。注释包含用户名,标记和一些粗体文本。

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

单词" Nancy"和"服装:"应分别为灰色和橙色,"第2季,第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];

有人可以帮我一个代码,告诉我如何用所需的格式来实现这个例句吗?

2 个答案:

答案 0 :(得分:0)

你必须添加逻辑,因为我非常确定你不想总是颜色/粗体这个特定的单词,但是这里你举一个简单的例子:< / p>

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];

答案 1 :(得分:0)

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;