TTT归功于Label Multi-coloured Font帮助

时间:2011-05-21 10:00:30

标签: iphone objective-c xcode nsattributedstring

-(UITableViewCell*) makeLikeCell
 {
    // Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle]      loadNibNamed:@"SpotlightLikesTableViewCell" owner: self options: nil];

// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
UITableViewCell *cell = [topLevelObjects objectAtIndex:0];


NSString *likeText = [likesAndComments objectAtIndex: kLikeRow];

TTTAttributedLabel *likeLabel = [[[TTTAttributedLabel alloc] initWithFrame:CGRectZero] autorelease];
likeLabel = (TTTAttributedLabel*) [cell viewWithTag: kCaptionTag];
likeLabel.textColor = [UIColor blueColor];
likeLabel.lineBreakMode = UILineBreakModeWordWrap;
[likeLabel setFont: [UIFont fontWithName: @"Helvetica Neue" size: 10]];

[likeLabel setText: likeText afterInheritingLabelAttributesAndConfiguringWithBlock: ^NSAttributedString *(NSMutableAttributedString *mutableAttributedString) {
    NSRange colorRange = [[mutableAttributedString string] rangeOfString: @" like this photo." options: NSCaseInsensitiveSearch];

    [mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName value:(id)[[UIColor grayColor] CGColor] range:colorRange];
    return mutableAttributedString; }];

return cell;
}

我在项目中添加了TTT属性标签。我希望有2种不同的字体颜色来显示“喜欢”。但是我的项目一直在崩溃。要格式化的示例字符串将是:“andrew,john,amos喜欢这张照片。”

有什么建议吗? enter image description here

2 个答案:

答案 0 :(得分:5)

像这样使用

[likeLabel setText:likeText afterInheritingLabelAttributesAndConfiguringWithBlock: ^(NSMutableAttributedString *mutableAttributedString) {
    NSRange colorRange = [likeText rangeOfString: @"like this photo." options: NSCaseInsensitiveSearch];
    if (colorRange.location != NSNotFound) {
        [mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName value:(id)[[UIColor grayColor] CGColor] range:colorRange];
    }
    return mutableAttributedString; 
}];

答案 1 :(得分:0)

有一种方法可以设置不同/多种字体&其他属性,如使用NSMutableAttributedStrin的Label上的颜色。请参阅Multiple Font & Color for string & Display the string on Label

上的答案