我想存儲具有不同屬性的不同字符串,並將它們全部存儲在一個數組中,然後將對象顯示在一個標籤中,但每個對象都具有其各自的屬性。如何使用NSAttributedStrings創建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;
你明白了我的觀點。但是我仍然有一個問題:使用你的例子,'myStrings'是否也包含每個對象所具有的屬性,或者只包含這些對象?因爲我必須有對象和屬性。 –
我聲明'myStrings'有一個'NSAttributedString'對象的數組。我不知道你的意思是「對象和屬性」。這就是爲什麼你的問題如此不清楚。您需要在您的問題中提供更多信息。 – rmaddy
好吧,假設我有5個屬性,每個屬於一個國家,每個國家都有不同的屬性。我的第一個目標是將這些字符串存儲在數組或字典中。我的第一個問題來了:是否有可能在數組或字典中存儲屬性的字符串?比我需要在一個uilabel中顯示數組或對象中的所有對象,但必須顯示它們的相應屬性。使用我的例子,它將是一個顯示fife contry名稱的標籤,並且每個標籤都具有不同的顏色。 –