为什么使用预测输入多次调用shouldChangeTextInRange? [英] Why does shouldChangeTextInRange get called multiple times using predictive input?

查看:907
本文介绍了为什么使用预测输入多次调用shouldChangeTextInRange?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iOS8的预测输入多次调用 UITextView 的以下委托方法,导致所选单词多次插入到视图中。

The predictive-input of iOS8 calls the following delegate method of UITextView multiple times resulting in the selected word being inserted multiple times into the view.

此代码适用于键入单个字母和复制/粘贴,但不适用于使用预测输入栏;为什么不呢?

This code works for typing single letters and copy/paste but not when using the predictive-input bar; why not?

- (BOOL) textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    textView.text = [textView.text stringByReplacingCharactersInRange:range withString:text];
    return false;
}

使用此代码;如果我输入一个空的UITextView并点击预测文本(自动完成)视图中的The,它会通过对此方法进行三次调用将The插入到视图中。每次调用传入的参数是:

With this code; if I enter an empty UITextView and tap on "The" in the predictive text (autocomplete) view it inserts "The The" into the view by way of making three calls on this method. The parameters passed in for each call are:


  • 范围: {0,0} text: @The

  • 范围: {0,0} text: @The

  • 范围: {3,0} text: @

  • range : {0,0} text : @"The"
  • range : {0,0} text : @"The"
  • range : {3,0} text : @" "

我能理解的空间;但为什么要两次插入The?

The space I can understand; but why insert "The" twice?

推荐答案

我遇到了同样的问题。看来,使用预测文本,在该委托方法中设置textView.text会再次触发对该委托方法的立即调用(据我所知,这只发生在预测文本中)。

I got this same issue. It appears that with predictive text, setting textView.text in that delegate method triggers an immediate call to that delegate method again (this only happens with predictive text as far as I know).

我修复它只是用一个警卫围绕我的textView更改:

I fixed it by just surrounding my textView changes with a guard:

private var hack_shouldIgnorePredictiveInput = false

func textView(textView: UITextView!, shouldChangeTextInRange range: NSRange, replacementText text: String!) -> Bool {
    if hack_shouldIgnorePredictiveInput {
        hack_shouldIgnorePredictiveInput = false
        return false
    }

    hack_shouldIgnorePredictiveInput = true

    textView.text = "" // Modify text however you need. This will cause shouldChangeTextInRange to be called again, but it will be ignored thanks to hack_shouldIgnorePredictiveInput

    hack_shouldIgnorePredictiveInput = false

    return false
}

这篇关于为什么使用预测输入多次调用shouldChangeTextInRange?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆