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/