objective-c - 为什么使用预测输入会多次调用 shouldChangeTextInRange?

标签 objective-c ios8 uitextview

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

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

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

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

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

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

最佳答案

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

我通过用保护包围我的 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
}

关于objective-c - 为什么使用预测输入会多次调用 shouldChangeTextInRange?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26482036/

相关文章:

iphone - 套接字超时 - 需要帮助

objective-c - NSArray 是否复制对象?

快速 iMessage 风格的键盘输入

IOS 8 NSLocationAlwaysUsageDescription 自定义翻译

html - 如何在 TextView 中显示 HTML 文本

iphone - 如何完全禁用 UITextView 的滚动?

objective-c - 枚举对象与选项 :usingBlock: causing frequent unexplained freezes

iPhone 加载 View "slide effect"

ios - 在 iOS 模拟器之间同步 NSUserDefaults

iphone - 将 UITextview 添加为工具栏项