为什么使用预测输入多次调用shouldChangeTextInRange?

Wex*_*Wex 10 objective-c uitextview ios8

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

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

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

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

  • 范围:{0,0}文字:@"The"
  • 范围:{0,0}文字:@"The"
  • 范围:{3,0}文字:@" "

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

Ric*_*ble 17

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

我通过围绕我的textView更改来修复它:

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
}
Run Code Online (Sandbox Code Playgroud)