0

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

有什么建议么?

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

2 回答 2

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;
于 2013-01-23T23:20:17.300 回答
0

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

于 2013-01-23T22:37:39.257 回答