2014-01-09 159 views
0

我必須格式化爲3種樣式的字符串。該字符串是這樣的:帶動態範圍的NSAttributedString

1.0000 of 2.000 

1.0000有前景的紅色,of具有更小的字體和2.000必須是綠色的。

問題是這些數字可能在任何範圍內,所以第一個和第二個數字可以由4,5,6組成任何字符。

如何執行這樣的字符串格式化?

編輯----------------- 我添加了一些信息:字符串保持其格式。例如,這可能是其模板:N of N

+1

一點的更多信息將是有益的,就像是在類似的字符串,比如yyyyy的xxxxx,或者'單詞'可能不同。 – n00bProgrammer

+0

我已經添加了一些關於字符串格式的信息。 – MatterGoal

回答

3

使用NSScanner或NSRegularExpression來查找數字表達式及其片段。

5

讓假設你有三個:

NSString *string0 = @"1.0000"; NSString *string1 = @"of"; NSString 
*string2 = @"2.000"; 


NSString *text = [NSString stringWithFormat:@"%@ %@ %@", 
          string0 ,string1,string2]; 

     //whole String attribute 
     NSDictionary *attribs = @{ 
            NSForegroundColorAttributeName:[UIColor whiteColor], 
            NSFontAttributeName:[UIFont systemFontOfSize:10] 
            }; 

     NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs]; 

     NSRange string0Range = [text rangeOfString:string0]; 
     NSRange string1Range = [text rangeOfString:string1]; 
     NSRange string2Range = [text rangeOfString:string2]; 
     [attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:15] range:string0Range]; 
     [attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont systemFontOfSize:12] range:string1Range]; [attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor], NSFontAttributeName:[UIFont systemFontOfSize:15] range:string2Range]; 
     [yourLabel setAttributedText:attributedText]; 
+0

偉大的答案最適合我。謝啦 –

1

最簡單的解決辦法是:

NSString* myString = @"12.345 of 56.789"; 

NSMutableAttributedString * tempString = [[NSMutableAttributedString alloc] initWithString:myString]; 

NSRange midrange = [tempString.string rangeOfString:@"of"]; 



[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6], 
          NSForegroundColorAttributeName : [UIColor redColor]} 
        range:NSMakeRange(0, midrange.location)]; 

[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6], 
          NSForegroundColorAttributeName : [UIColor blackColor]} 
        range:midrange]; 

[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6], 
          NSForegroundColorAttributeName : [UIColor greenColor]} 
        range:NSMakeRange(midrange.location + midrange.length, tempString.length - midrange.location - midrange.length)]; 

yourElement.attributedText = tempString; 

enter image description here