2013-01-23 22 views
0

我想存儲具有不同屬性的不同字符串,並將它們全部存儲在一個數組中,然後將對象顯示在一個標籤中,但每個對象都具有其各自的屬性。如何使用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; 

回答

4

你的問題很不清楚。但根據你對格里坦的回答的評論,你的目標更清晰。

如果您有一個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; 
+0

你明白了我的觀點。但是我仍然有一個問題:使用你的例子,'myStrings'是否也包含每個對象所具有的屬性,或者只包含這些對象?因爲我必須有對象和屬性。 –

+0

我聲明'myStrings'有一個'NSAttributedString'對象的數組。我不知道你的意思是「對象和屬性」。這就是爲什麼你的問題如此不清楚。您需要在您的問題中提供更多信息。 – rmaddy

+0

好吧,假設我有5個屬性,每個屬於一個國家,每個國家都有不同的屬性。我的第一個目標是將這些字符串存儲在數組或字典中。我的第一個問題來了:是否有可能在數組或字典中存儲屬性的字符串?比我需要在一個uilabel中顯示數組或對象中的所有對象,但必須顯示它們的相應屬性。使用我的例子,它將是一個顯示fife contry名稱的標籤,並且每個標籤都具有不同的顏色。 –

0

的UILabel得出解決方案只支持一個NSAttributedString。我認爲你可以做的是爲陣列上的每個字符串並排放置多個UILabel

+0

是的我知道,但我知道我可以在一個標籤中顯示數組的內容,如將其描述轉換爲nsstring,然後顯示標籤中的所有對象。問題是:我可以將多個nsattributedstrings存儲在一個數組或字典中,並將它們全部顯示在一個帶有屬性的標籤中,並得到它?但謝謝你的回覆。 –

+0

嗯,也許你可以擴展UILabel並編寫你自己的類 - 叫它UILabelMultiString或其他東西。然後重寫它呈現字符串的部分以支持多個NSAttributedString。 – gerrytan

+0

感謝gerrytan,但rmaddy解決方案做到了! –