2014-01-09 2 views
0

문자열을 3 가지 형식으로 형식화해야합니다. of는 작은 글꼴을 가지고 있으며, 2.000 녹색이어야한다,동적 범위가있는 NSAttributedString

1.0000 of 2.000 

1.0000 전경 붉은 색깔이있다 : 문자열은 같은입니다.

숫자가 임의의 범위에있을 수 있으므로 첫 번째 숫자와 두 번째 숫자는 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

관련 문제