假设我有这个:
self.dictionary = [NSMutableArray arrayWithObjects:
@"blah",
@"blah",
@"blah (blah)",
@"blah",
@"blah",
nil];
在第三个对象中,我希望第一个“blah”具有更大的字体大小和黑色字体颜色。但是,我希望括号中的第二个“blah”具有更小的尺寸和灰色。我该怎么做呢?它甚至可能吗?
答案 0 :(得分:0)
您想使用NSMutableAttributedString。
您只需连接所有字符串和每个子字符串,找出您想要的属性,而不是调用- setAttributes:range:
。
答案 1 :(得分:0)
NSString不允许您拥有特定的样式。如果您的字符串需要具有样式/属性,则必须使用NSAttributedString。
答案 2 :(得分:0)
现在只存储NSString
个对象。 NSString没有附加任何字体。如果您想保留字体信息,可以查看NSAttributedString
课程 - https://developer.apple.com/Library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/index.html
所以你的代码看起来像是:
self.items = @[
[[NSAttributedString alloc] initWithString: @"bla" attributes: @{
NSFontAttributeName: [UIFont systemFontOfSize: 12.0],
NSForegroundColorAttributeName: [UIColor blackColor]
}],
[[NSAttributedString alloc] initWithString: @"bla" attributes: @{
NSFontAttributeName: [UIFont systemFontOfSize: 14.0],
NSForegroundColorAttributeName: [UIColor grayColor]
}]
];
答案 3 :(得分:0)
尝试以下代码: -
NSArray *yourArr= @[@"blah",
@"blah",
@"blah (blah)",
@"blah",
@"blah"];
for (NSString *word in yourArr)
{
if ([word isEqualToString:@"blah (blah)"])
{
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:[word componentsSeparatedByString:@" "][0] attributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:18]}]];
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:@" "]];
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:[word componentsSeparatedByString:@" "][1] attributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:14],NSForegroundColorAttributeName:[NSColor grayColor]}]];
}
else
{
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:word]];
}
[yourAtt appendAttributedString:[[NSAttributedString alloc]initWithString:@",\n"]];
}
self.yourAttStr=yourAtt;