내 프로그램에 구문 강조를 추가하려고합니다.
나는 하이라이트를 추가하려면이 코드를 사용하고 있습니다 :UITextView에서 UILabels이 올바르게 오버레이되지 않음
-(void)highlightWord:(NSString *)word: (UIColor *)color {
int amount = textDisplay.text.length;
NSString *newString = textDisplay.text;
NSUInteger count = 0, length = amount;
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [textDisplay.text rangeOfString: word options:NSLiteralSearch range:range];
if(range.location != NSNotFound)
{
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
while (count != 0) {
count--;
NSRange highlight = [newString rangeOfString:word];
newString = [textDisplay.text stringByReplacingCharactersInRange:highlight withString:@" "];
UILabel *view1 = [[UILabel alloc] initWithFrame:[self frameOfTextRange:highlight inTextView:textDisplay]];
view1.text = word;
view1.textColor = color;
view1.font = [UIFont fontWithName:@"System" size: 14.0];
view1.backgroundColor = [UIColor clearColor];
view1.textAlignment = UITextAlignmentLeft;
[textDisplay addSubview:view1];
}
}
- (IBAction)highlighString:(id)sender {
for (UIView *subview in [textDisplay subviews]){
if ([subview isKindOfClass:[UILabel class]]){
[subview removeFromSuperview];
}
}
[self highlightWord:@"test" :[UIColor blueColor]];
[self highlightWord:@"this" :[UIColor redColor]];
[self highlightWord:@"is" :[UIColor grayColor]];
[self highlightWord:@"a" :[UIColor greenColor]];
}
@end
을하지만이 이상한 결과를 초래할 것 :
원하는 결과를이 원활 색깔의 레이블을 겹쳐 있다는 것입니다.
UITextView에서 레이블 (글꼴에 다른 글꼴 또는 속성이있을 수 있음)을 던지면 항상 거추장 스럽거나 위험 할 수 있습니다. 왜 [속성 문자열을 허용하는 UITextView 대체] (http://stackoverflow.com/a/8961839/981049)를 사용하지 않을까요? –
필자는 필자가 필요로하는 것을 복사하고 붙이기 만하면되지만, 그 밖의 모든 것이 실패하면 나는 이것을 사용할 수있다. – Sirens
이 작업을 수행하는 방법이 너무 복잡합니다. 내가 당신에게로 연결시켜 줄께 -> http://stackoverflow.com/questions/2218415/nstextview-syntax-highlighting 원인 문자열 사용 –