2013-05-09 15 views
1

如何更改我的UITableViewCell的detailTextLabel中的一個字符串的字體?更改單獨字符串的字體detailTextLabel

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

cell.detailTextLabel.text = detailStr; 

我基本上希望post.score字符串是一個顏色和post.domain字符串是另一個。

+0

您是否檢查了我的答案?我很確定它會解決你的問題。 – Bhavin 2013-05-15 13:49:33

回答

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

如果你樂於使用iOS6的+的API,然後檢查了NSAttributedString和使用cell.detailTextLabel.attributedText = ...

1

我認爲你在尋找setAttributedText:方法UILabel。您可以將NSAttributedString傳遞給它,以便以不同方式設定字符串的不同部分。
我在下面寫了一個示例,應該做你所要求的。

NSAttributedString *scoreAttributedString = [[NSAttributedString alloc] initWithString:[post score] attributes:@{NSForegroundColorAttributeName: [UIColor redColor]}]; 
NSAttributedString *domainAttributedString = [[NSAttributedString alloc] initWithString:[post domain] attributes:@{NSForegroundColorAttributeName: [UIColor greenColor]}]; 

NSMutableAttributedString *detailMutableAttributedString = [[NSMutableAttributedString alloc] init]; 
[detailMutableAttributedString appendAttributedString:scoreAttributedString]; 
[detailMutableAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]]; 
[detailMutableAttributedString appendAttributedString:domainAttributedString]; 

[[cell detailTextLabel] setAttributedText:detailMutableAttributedString]; 
+0

對於我的項目需要,這是對我有用的答案。謝謝。 – ChrisOSX 2017-03-08 20:54:09