我正在使用UIMenuItem和UIMenuController为我的UITextView添加一个高亮功能,因此用户可以更改所选文本的背景颜色,如下图所示: UITextView中的Setected文本,具有用户可用的突出显示功能: UITextV
> UITextView中的Setected文本,具有用户可用的突出显示功能:
> UITextView中突出显示的文本,使用新的背景颜色,用户在点击突出显示功能后选择:
在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中,文本选择正在跳跃.当我使用UIMenuItem和UIMenuController中的突出显示功能时,它也会跳转到另一个UITextView偏移量.
如何在iOS 8中解决此问题?
我最终解决了这个问题,如果其他人有更优雅的解决方案,请告诉我:- (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;
}
}
