iOS – 使用TTTAttributedLabel设置两个颜色文本

我正在创建具有标签的iOS应用程序.我想设置两种颜色.一个用于第一部分,另一个用于剩余部分.
我在Stack over flow中看到了一些消息,TTTAttributedLabel能够为文本设置多种颜色.我的文字就像“ABC> def”.对于“ABC”,我想设置棕色和“def”,我想设置白色.
我怎么设置?

解决方法

NSString* text = @"ABC > def";
attributedLabel = [[[TTTAttributedLabel alloc] initWithFrame:frame] autorelease];
attributedLabel.numberOfLines = 0;
attributedLabel.lineBreakMode = UILineBreakModeWordWrap;
attributedLabel.fontColor = [UIColor brownColor];
[attributedLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^(NSMutableAttributedString *mutableAttributedString) {
    NSRange whiteRange = [text rangeOfString:@"def"];
    if (whiteRange.location != NSNotFound) {
    // Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
        [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor whiteColor].CGColor range:whiteRange];
    }

    return mutableAttributedString;
}];

[attributedLabel sizeToFit]; //this may not be needed if the frame provided is large enough

在字符串中搜索“def”,并将该范围的文本的前景色设置为白色.希望这可以帮助.我昨天才刚刚学会了这个.在试图为自己解决问题时遇到了你的问题.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...