我正在尝试向我的程序添加语法高亮显示。
我使用这个代码增添亮点:在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)? – 2012-07-22 00:25:46
我想除了我*需要*复制和粘贴,但如果一切都失败了,我可以使用这个。 – Sirens 2012-07-22 00:29:39
你这样做的方法太复杂了。让我指导你 - > http://stackoverflow.com/questions/2218415/nstextview-syntax-highlighting使用属性字符串 – 2012-07-22 00:30:47