Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/103.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS-使用TTtatAttributedLabel设置双色文本_Ios_Uilabel_Nsattributedstring - Fatal编程技术网

iOS-使用TTtatAttributedLabel设置双色文本

iOS-使用TTtatAttributedLabel设置双色文本,ios,uilabel,nsattributedstring,Ios,Uilabel,Nsattributedstring,我正在创建带有标签的iOS应用程序。我想设置两种颜色。第一部分一种颜色,其余部分另一种颜色。 我在Stack over flow中看到了一些消息,它们能够为文本设置多种颜色。我的文本将类似于“ABC>def”。对于“ABC”,我要设置棕色,对于“def”,我要设置白色。 我该怎么设置呢 NSString* text = @"ABC > def"; attributedLabel = [[[TTTAttributedLabel alloc] initWithFrame:frame] auto

我正在创建带有标签的iOS应用程序。我想设置两种颜色。第一部分一种颜色,其余部分另一种颜色。
我在Stack over flow中看到了一些消息,它们能够为文本设置多种颜色。我的文本将类似于“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”,并在该范围内将文本的前景色设置为白色。希望这有帮助。我昨天才知道。我在试图自己解决问题时遇到了您的问题。

您可以使用TTTRegexAttributedLabel,网址为:。(基于TTtatAttributedLabel,但更易于与正则表达式一起使用)


谢谢你提供答案。我的问题通过使用TTTAttributedLabel解决了。以后,我会记住使用您建议的库。别忘了在块的末尾返回mutableAttributedString。@djibouti33谢谢,不知道我怎么会错过这个。现在编辑了答案,将其包括在内。任何人都有Swift的解决方案吗?@guru我可以将其转换为Swift,但从iOS 6开始,UILabel上就提供了AttributeText属性
  //SET FONT ONLY ON FIRST MATCH REGEX
  TTTRegexAttributedLabel *label = [[TTTRegexAttributedLabel alloc] init];
  label.textColor = [UIColor whiteColor];
  NSString *s = @"ABC > def";
  [self.label setText:s withFirstMatchRegex:@"^[a-zA-Z ]*>"
                        withFont:[UIFont systemFontOfSize:12]
                        withColor:[UIColor brownColor]];