【问题标题】:TTT attributed Label Multi- colored Font helpTTT 属性标签多色字体帮助
【发布时间】:2011-05-21 10:00:29
【问题描述】:
-(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 like this photo。”

有什么建议吗?

【问题讨论】:

  • 您能否更具体地说明控制台崩溃时会吐出的内容?如果你在断点的情况下运行,你可以在它崩溃后执行bt 来获得回溯吗?我的第一个想法是,您可能会遇到问题,通过将 colorRange 传递给 -addAttribute:value:range 而不检查是否找不到字符串 (colorRange.location == NSNotFound)

标签: iphone objective-c xcode nsattributedstring


【解决方案1】:

这样使用

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

【讨论】:

  • 嗨@inder 我可以使用 [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[[TEXT_LINK_COLOR] CGColor] range:whiteRange];其中文本链接颜色是我在一个 .h 文件中采用的常量
【解决方案2】:

有一种方法可以使用 NSMutableAttributedStrin 在标签上设置不同/多种字体和其他属性,例如颜色。参考我在Multiple Font & Color for string & Display the string on Label的回答

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2021-01-26
    相关资源
    最近更新 更多