2014-01-28 2 views
0

NSString에있는 특정 단어 집합을 강조 표시하거나 밑줄을 그어 싶습니다. 나는 그 단어가 존재 하는지를 감지 할 수있다, 나는 그것들을 강조 표시 할 수 없다.문자열의 특정 단어 강조 표시 또는 밑줄

NSString * wordString = [NSString stringWithFormat:@"%@", [self.myArray componentsJoinedByString:@"\n"]]; 

self.myLabel.text = wordString; 

if ([wordString rangeOfString:@"Base Mix"].location == NSNotFound) 
{ 
    NSLog(@"string does not contain base mix"); 
} 
else 
{ 
    NSLog(@"string contains base mix!"); 

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:wordString]; 

    NSString * editedString = [NSString stringWithFormat:@"%lu", (unsigned long)[wordString rangeOfString:@"Base Mix"].location]; 

    NSRange theRange = NSMakeRange(0, [editedString length]); 

    [string beginEditing]; 
    [string removeAttribute:NSForegroundColorAttributeName range:theRange]; 
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:theRange]; 
    [string endEditing]; 

    [self.myLabel setAttributedText:string]; 
} 

이 코드는 올바른 경로에 더 가깝습니다. 강조 표시된 문자가 보이지만 문자열의 첫 번째 문자이며 검색 한 단어가 아닙니다.

답변

4

NSUnderlineStyleAttributeNameNSUnderlineColorAttributeName 속성을 사용할 수 있습니다. 다음과 같이 사용할 수 있습니다 :

NSRange foundRange = [wordString rangeOfString:@"Base Mix"]; 
if (foundRange.location != NSNotFound) 
{ 
    [wordString beginEditing]; 
    [wordString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:foundRange]; 
    [wordString addAttribute:NSUnderlineColorAttributeName value:[NSColor redColor] range:foundRange]; 
    [wordString endEditing]; 
} 
0

NSAttributedString에서이 부분이 누락되었다고 생각합니다. 함께 시도해보십시오 Three20

2

NSAttributed 문자열과 관련된 아래 코드를 사용할 수 있습니다. 작품 만 ios6 +

NSString *tem = @"String with base Mix dfsdfsd "; 
NSString *substring = @"base Mix"; 
NSRange range; 
if ((range =[tem rangeOfString:substring]).location == NSNotFound) 
{ 
     NSLog(@"string does not contain base mix"); 
} 
else 
{ 
     NSMutableAttributedString *temString=[[NSMutableAttributedString alloc]initWithString:tem]; 
     [temString addAttribute:NSUnderlineStyleAttributeName 
            value:[NSNumber numberWithInt:1] 
            range:(NSRange){range.location,substring.length}]; 
     NSLog(@"%@",temString); 
     self.yourLabel.attributedText = temString; 
}  
관련 문제