更改单独字符串detailTextLabel的字体

时间:2013-05-09 14:17:26

标签: ios objective-c cocoa-touch

如何在UITableViewCell的detailTextLabel中更改一个字符串的字体?

NSString *detailStr = [NSString stringWithFormat:@"%@ %@",post.score,post.domain];

cell.detailTextLabel.text = detailStr;

我基本上希望post.score字符串为一种颜色而post.domain字符串为另一种颜色。

3 个答案:

答案 0 :(得分:2)

答案:NSAttributedString

试试这个:

int count1 = [post.score length];
int count2 = [post.domain length];
NSMutableAttributedString *textLabelStr = [[NSMutableAttributedString alloc] initWithString:@"%@ %@",post.score,post.domain];
[textLabelStr setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:17]} range:NSMakeRange(0, count1)];
[textLabelStr setAttributes:@{NSForegroundColorAttributeName : [UIColor blueColor], NSFontAttributeName : [UIFont systemFontOfSize:17]} range:NSMakeRange(count1 + 1, count2)];
cell.detailTextLabel.attributedText = textLabelStr;

注意:未经测试,但请编写代码以帮助您。

答案 1 :(得分:1)

如果您愿意使用iOS6 + API,请查看NSAttributedString并使用cell.detailTextLabel.attributedText = ...

答案 2 :(得分:1)

我认为您正在寻找setAttributedText:的{​​{1}}方法。您可以将UILabel传递给它,以便以不同方式对字符串的不同部分进行样式化 我在下面写了一个样本,应该做你想要的。

NSAttributedString