如何使用NSAttributedStrings创建NSarray但保留数组中的属性?

时间:2013-01-23 22:22:36

标签: objective-c nsarray uilabel nsattributedstring

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

有什么建议吗?

编辑:来自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;

2 个答案:

答案 0 :(得分:4)

你的问题很不清楚。但根据你对gerrytan答案的评论,你的目标更清晰。

如果你有一组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;

答案 1 :(得分:0)

UILabel仅支持一个NSAttributedString。我认为你可以做的是为阵列上的每个字符串并排放置多个UILabel