2013-07-16 51 views

回答

10
NSString *twoWords = @"Green Red"; 
    NSArray *components = [twoWords componentsSeparatedByString:@" "]; 
    NSRange greenRange = [twoWords rangeOfString:[components objectAtIndex:0]]; 
    NSRange redRange = [twoWords rangeOfString:[components objectAtIndex:1]]; 

    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:twoWords]; 

    [attrString beginEditing]; 
    [attrString addAttribute: NSForegroundColorAttributeName 
         value:[UIColor greenColor] 
         range:greenRange]; 

    [attrString addAttribute: NSForegroundColorAttributeName 
         value:[UIColor redColor] 
         range:greenRange]; 

    [attrString endEditing]; 

然后可以使用直接在一个UILabel attrString(>的iOS 6,检查Apple Documentation)。

+0

kCTStrokeColorAttributeName < - 看起来像设置统计员的... ...的addAttribute需要一个字符串值,统计员是号码 –

+0

@A'saDickens你是对的。只是改变了。 – cescofry

0

This question地址获取字符串的一部分,你需要做的。尽管如此,您可以使用this question来了解如何更改颜色,而不是使用BOLD修改文本。

7

最简单的方法是在iOS 6.0或更高版本中使用。你会分配其中的一个,并在titleLabel(或任何其他持有文本的对象)中分配UITableViewCell。如果您使用的titleLabel你可以这样做:

[cell.titleLabel setAttributedText:yourAttributedString]; 

要设置与NSAttributedString的颜色,这样做:

NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:stringToManipulate]; 
[attributedString beginEditing]; 
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, widthOfFisrtWord)]; 
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(widthOfFisrtWord, widthOfSecondWord)]; 
[attributedString endEditing]; 

注意上面使用NSMakeRange提供的范围不会是您需要的范围。您必须根据自己的需要更改范围,具体取决于两个单词之间是否有空格或其他字符。

苹果文档:

+0

哦,非常感谢编辑:D我只是看着如何做到这一点不集群的答案,我能够点击编辑,看看你做了格式化,非常有义务 –

+0

纠正我,如果我错了,但NSAttributedString不是这样做的方式。链接的文档似乎无法指定属性的范围。但是,您的代码使用NSMutableAttributedString,其文档的范围是:https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSMutableAttributedString_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableAttributedString/addAttribute:值:范围: – prewett

+0

这是正确的,在我写了答案的时候,我想我没有注意 –

相关问题