我正在尝试向我的程序添加语法高亮。
我正在使用此代码添加亮点:
-(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
但这似乎会导致奇怪的结果:
期望的结果是它无缝地覆盖到彩色标签。