我正在創建具有標籤的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