目标 c - 如何使用 NSAttributedString 创建 NSarray,但将属性保留在数组中



我想存储具有不同属性的不同字符串,并将它们存储在一个数组中,然后在一个标签中显示对象,但每个对象都有其各自的属性。

有什么建议吗?

编辑:从rmaddy的答案得出的解决方案

NSDictionary *redAttrs    = @{NSForegroundColorAttributeName:[UIColor redColor]};
NSDictionary *greenAttrs  = @{NSForegroundColorAttributeName:[UIColor colorWithRed:0.118 green:0.506 blue:0.000 alpha:1.000]};
NSDictionary *orangeAttrs = @{NSForegroundColorAttributeName:[UIColor orangeColor]};
NSString *stringUm = @"Brazil";
NSString *stringDois = @"USA";
NSString *stringTres = @"England";
NSMutableAttributedString *redString = [[NSMutableAttributedString alloc] initWithString:stringUm];
[redString setAttributes:redAttrs range:NSMakeRange(0,4)];
NSMutableAttributedString *greenString = [[NSMutableAttributedString alloc] initWithString:stringDois];
[greenString setAttributes:greenAttrs range:NSMakeRange(0,2)];
NSMutableAttributedString *orangeString = [[NSMutableAttributedString alloc] initWithString:stringTres];
[orangeString setAttributes:orangeAttrs range:NSMakeRange(0,4)];

NSArray *myStrings = [[NSArray alloc] initWithObjects:redString, greenString, orangeString, nil];
NSLog(@"%@", [myStrings description]);
NSMutableAttributedString *result = [[NSMutableAttributedString alloc]init];
NSAttributedString *delimiter = [[NSAttributedString alloc] initWithString: @", "];
for (NSAttributedString *str  in myStrings) {
    if (result.length) {
        [result appendAttributedString:delimiter];
    }
    [result appendAttributedString:str];
}
_lblUm.attributedText = result;

你的问题很不清楚。但根据你对格里坦回答的评论,你的目标更明确。

如果您有 NSAttributedString 对象的数组,则可以通过将它们与 NSMutableAttributedString 一起追加来创建单个字符串。

NSArray *myStrings = ... // your array of NSAttributedString objects
NSMutableAttributedString *result = [[NSMutableAttributedString alloc] init];
// Put this delimiter between each string - change as desired
NSAttributedString *delimiter = [[NSAttributedString alloc] initWithString:@", "];
for (NSAttributeString *str in myStrings) {
    if (result.length) {
        [result appendAttributedString:delimiter];
    }
    [result appendAttributedString:str];
}
myLabel.attributedText = result;

UILabel 仅支持一个 NSAttributedString。我认为您可以做的是为数组上的每个字符串并排放置多个 UILabel,

最新更新