ios - iOS 8中的UITextView文本选择和高亮跳转

标签 ios iphone ios7 ios8 uitextview

我正在使用 UIMenuItemUIMenuController 向我的 UITextView 添加一个highlight 功能,所以用户可以更改所选文本的背景颜色,如下图所示:

  • UITextView 中的选定文本,具有可供用户使用的突出显示功能:

Setected text in <code>UITextView</code>

  • UITextView 中使用新的背景颜色突出显示文本,由用户在点击突出显示 功能后选择: Highlighted text in <code>UITextView</code> with a new background color

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 中,文本选择是跳跃的。当我使用 UIMenuItemUIMenuControllerhighlight 功能时,它也会跳转到另一个 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/

相关文章:

ios - 自动触发滚动两个不同尺寸的uiwebview

ios - 自定义标签栏 Swift

ios - Storekit Appstore 购买促销

iphone - 在 UIWebview 中加载字符串

ios - EXC_BAD_ACCESS code=2 Xcode 中自定义类初始化错误

ios - 如何在 iOS 7 中设置焦点文本字段的样式

ios - ARC dealloc 在主线程以外的线程上调用

ios - 应用标题旁边的红点?

iphone - 将数据上传至 iCloud

ios - 应用程序启动后启动图标略有不同