UITextView文本select和高亮在iOS 8中跳跃

我正在使用UIMenuItemUIMenuController向我的UITextView添加高亮function,因此用户可以更改所选文本的背景颜色 ,如下图所示:

  • UITextView使用高亮function在用户中检测到文本:

在<code> UITextView </ code>中检测到了文本

  • UITextView突出显示的文本具有新的背景色,用户在点击突出显示的特征后select: 使用新的背景色在<code> UITextView </ code>中突出显示文本

iOS 7中 ,以下代码正在完美地完成此任务:

 - (void)viewDidLoad { [super viewDidLoad]; UIMenuItem *highlightMenuItem = [[UIMenuItem alloc] initWithTitle:@"Highlight" action:@selector(highlight)]; [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:highlightMenuItem]]; } - (void)highlight { NSRange selectedTextRange = self.textView.selectedRange; [attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:selectedTextRange]; // iOS 7 fix, NOT working in iOS 8 self.textView.scrollEnabled = NO; self.textView.attributedText = attributedString; self.textView.scrollEnabled = YES; } 

但在iOS 8中 ,文本select正在跳跃。 当我使用UIMenuItemUIMenuController高亮function时,它也会跳转到另一个UITextView偏移量。

我如何解决这个问题在iOS 8

我最终解决了这个问题,如果别人有更优雅的解决scheme,请告诉我:

 - (void)viewDidLoad { [super viewDidLoad]; UIMenuItem *highlightMenuItem = [[UIMenuItem alloc] initWithTitle:@"Highlight" action:@selector(highlight)]; [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:highlightMenuItem]]; float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue]; if (sysVer >= 8.0) { self.textView.layoutManager.allowsNonContiguousLayout = NO; } } - (void)highlight { NSRange selectedTextRange = self.textView.selectedRange; [attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:selectedTextRange]; float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue]; if (sysVer < 8.0) { // iOS 7 fix self.textView.scrollEnabled = NO; self.textView.attributedText = attributedString; self.textView.scrollEnabled = YES; } else { self.textView.attributedText = attributedString; } } 

移动self.textView.scrollEnabled = NO; 到第一行的突出方法。

希望能帮助到你!