【发布时间】:2014-03-28 11:25:41
【问题描述】:
是否可以有一个NSString 的第一个单词具有一种字体大小/颜色,而下一个单词具有另一种字体大小和颜色?
我在想可能是NSAttributedString - 但不确定这是否可行?
我尝试将两个NSString 放入NSAttributedString - 但没有奏效。
正在寻找具有以下内容的 UILabel:
大字符串(小字符串)
工作示例
到目前为止,我想出了这个:
/* Set the Font Sizes */
UIFont *objectNameFont = [UIFont systemFontOfSize:14.f];
UIFont *itemsFont = [UIFont systemFontOfSize:12.f];
/* Create the attribute dictionaries */
NSDictionary *objectNameDict = [NSDictionary dictionaryWithObject:objectNameFont forKey:NSFontAttributeName];
NSDictionary *objectItemDict = [NSDictionary dictionaryWithObject:itemsFont forKey:NSFontAttributeName];
/* Create the string */
NSString *labelFullName = [NSString stringWithFormat:@"%@ (%@)", object.name, object.items];
/* Seperate the two strings */
NSArray *components = [labelFullName componentsSeparatedByString:@" ("];
NSRange objectNameRange = [labelFullName rangeOfString:[components objectAtIndex:0]];
NSRange objectItemRange = [labelFullName rangeOfString:[components objectAtIndex:1]];
/* Create the Attributed string */
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:labelFullName];
/* Start the editiong */
[attrString beginEditing];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor colorWithRed:0.667 green:0.667 blue:0.667 alpha:1] /*#aaaaaa*/
range:objectItemRange];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor colorWithRed:0.271 green:0.271 blue:0.271 alpha:1] /*#454545*/
range:objectNameRange];
[attrString addAttributes:objectNameDict range:objectNameRange];
[attrString addAttributes:objectItemDict range:objectItemRange];
[attrString endEditing];
cell.title.attributedText = attrString;
return cell;
这似乎可以按我的需要工作。但是,两个字符串“(”的分隔符是黑色的,我需要它与此处设置的 object.items 颜色相同:
[attrString addAttribute: NSForegroundColorAttributeName value:[UIColor colorWithRed:0.667 green:0.667 blue:0.667 alpha:1] /*#aaaaaa*/ range:objectItemRange];
找到解决方案
我找到了适合我的解决方案:
我拉出字符串并将它们放入 NSArray 并使用 objectAtIndex 获取它们的 NSRange 值来设置文本
有任何想法吗?
谢谢大家。
【问题讨论】:
-
使用属性字符串。
标签: ios objective-c nsstring