我正在创建具有标签的iOS应用程序。我想设置两种颜色。第一部分为其余部分,其余部分为其他颜色。
我已经看到Stack over flow中的一些消息,TTTAttributedLabel能够将多个颜色设置为文本。我的文本将会像“ABC> def”一样。对于“ABC”,我想设置棕色和“def”,我想设置白色。
我该如何设置?iOS - 使用TTTAttributedLabel设置两种颜色文本
8
A
回答
16
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”并将文本的前景色设置为该范围的白色。希望这可以帮助。我昨天才知道这件事。遇到你的问题,同时试图找出自己。
6
您可以使用TTTRegexAttributedLabel:https://github.com/kwent/TTTRegexAttributedLabel。 (基于TTTAttributedLabel,但更容易与正则表达式一起使用)
//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]];
+4
感谢您提供答案。我的问题通过使用TTTAttributedLabel解决。将来,我会记住使用您建议的库。 – Satyam 2012-11-19 10:58:34
相关问题
- 1. TTTAttributedLabel多种颜色
- 2. 在单个DataGridView中设置两种颜色文本单元格
- 3. 使用JColorChooser设置文本颜色
- 4. OpenGL:设置文本颜色?
- 5. iOS:导航栏标题 - 两种颜色
- 6. iOS,CGGradientCreateWithColorComponets设置RGBA颜色
- 7. TCPDF如何设置两种文字颜色?
- 8. iOS在两种颜色之间的点上找到颜色
- 9. 两种颜色值
- 10. sifr两种颜色
- 11. 如何在XML中为TextView中的文本设置两种不同的颜色?
- 12. c#设置2种颜色的treenode文本
- 13. 用于设置颜色的iOS宏
- 14. 如何使用OpenOffice使用PyUNO设置文本背景颜色
- 15. 使用VML,可以设置文本的颜色和位置吗?
- 16. 使用javascript检测颜色是否在两种颜色之间
- 17. 如何为textfield-ios设置两种不同的边框笔触颜色
- 18. TTTAttributedLabel的链接龙头颜色
- 19. iOS的7/8如何设置标签栏的文本颜色
- 20. iOS Swift 3:设置UISearchBar ScopeButton文本和背景颜色
- 21. Ios - 设置默认文本颜色和字体大小
- 22. iOS设备使用哪种颜色空间?
- 23. 如何设置文本颜色在OpenGL
- 24. 设置全局文本颜色?
- 25. wxPython StyledTextCtrl设置(部分)文本颜色
- 26. Android视图设置文本颜色
- 27. 如何设置ActionItem文本的颜色
- 28. 设置溢出菜单文本颜色
- 29. PyQt的 - 设置文本颜色为QTabWidget
- 30. 设置WKInterfacePicker颜色(文本或轮廓)
不要忘记在块的结尾处返回mutableAttributedString。 – djibouti33 2013-03-14 22:05:25
@ djibouti33谢谢,不知道我是如何错过了。编辑答案包括现在。 – DonnaLea 2013-03-15 00:00:17