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

前端之家收集整理的这篇文章主要介绍了iOS – 使用TTTAttributedLabel设置两个颜色文本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在创建具有标签的iOS应用程序.我想设置两种颜色.一个用于第一部分,另一个用于剩余部分.
我在Stack over flow中看到了一些消息,TTTAttributedLabel能够为文本设置多种颜色.我的文字就像“ABC> def”.对于“ABC”,我想设置棕色和“def”,我想设置白色.
我怎么设置?

解决方法

  1. NSString* text = @"ABC > def";
  2. attributedLabel = [[[TTTAttributedLabel alloc] initWithFrame:frame] autorelease];
  3. attributedLabel.numberOfLines = 0;
  4. attributedLabel.lineBreakMode = UILineBreakModeWordWrap;
  5. attributedLabel.fontColor = [UIColor brownColor];
  6. [attributedLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^(NSMutableAttributedString *mutableAttributedString) {
  7. NSRange whiteRange = [text rangeOfString:@"def"];
  8. if (whiteRange.location != NSNotFound) {
  9. // 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.
  10. [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor whiteColor].CGColor range:whiteRange];
  11. }
  12.  
  13. return mutableAttributedString;
  14. }];
  15.  
  16. [attributedLabel sizeToFit]; //this may not be needed if the frame provided is large enough

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

猜你在找的iOS相关文章