是否有可能有一个 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 值来设置文本
有任何想法吗?

谢谢大家。

最佳答案

是的,您可以拥有。

您还获得了该 NSAttributedString 的正确 Class 。

在以下代码中,使用了两种字体大小 12 和 15:

UIFont *font=[UIFont fontWithName:@"Arial" size:12.f];
NSDictionary *attrsDict=[NSDictionary dictionaryWithObject:font
                                forKey:NSFontAttributeName];
NSAttributedString *attribString=[[NSAttributedString alloc] initWithString:[words[0] substringFromIndex:1]  attributes:attrsDict];

UIFont *fontFirst=[UIFont fontWithName:@"Arial" size:15.f];
NSDictionary *attrsDictFirst=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSAttributedString *firstString=[[NSAttributedString alloc] initWithString:[attribString subStringToIndex:1]  attributes:attrsDictFirst];

[attribString replaceCharactersInRange:NSMakeRange(0, 1)  withString:firstString];

更多类似的问题是 herehere

10-08 12:26