本文介绍了UITextView文本选择和在iOS 8中突出显示跳跃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 UIMenuItem UIMenuController 向我添加突出显示功能 UITextView ,因此用户可以更改所选文本的背景颜色,如下图所示:

I'm using UIMenuItem and UIMenuController to add a highlight feature to my UITextView, so the user can change the background color of the selected text, as shown in the pictures bellow:


  • UITextView 中的检测文本,用户可以使用突出显示功能:

  • Setected text in UITextView with the highlight feature available to the user:

  • UITextView 中突出显示的文字用户在点击突出显示功能后选择的背景颜色:

  • Highlighted text in UITextView with a new background color, chosen by the user after tapping on the highlight feature:

iOS 7 以下代码正常工作完美地完成此任务:

In iOS 7 the following code is working perfectly to accomplish this task:

- (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 抵消。

But in iOS 8 the text selection is jumping. When I use the highlight feature from the UIMenuItem and UIMenuController it jumps also to another UITextView offset.

如何在 iOS 8 中解决此问题?

推荐答案

我最终解决了这个问题,如果其他人有更优雅的解决方案,请告诉我:

I ended up solving my problem like this, and if someone else has a more elegant solution please let me know:

- (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;
    }
}

这篇关于UITextView文本选择和在iOS 8中突出显示跳跃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 04:38