我正在使用 UIMenuItem
和 UIMenuController
向我的 UITextView
添加一个highlight 功能,所以用户可以更改所选文本的背景颜色,如下图所示:
UITextView
中的选定文本,具有可供用户使用的突出显示功能:
- 在
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
的 highlight 功能时,它也会跳转到另一个 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;
}
}
关于ios - iOS 8中的UITextView文本选择和高亮跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26454037/