iOS 13 崩溃与 SwipeKeyboard 和文本字段 :shouldChangeCharactersIn:

标签 ios uitextfield ios13

在 iOS 13 中,当实现 shouldChangeCharactersIn通过 UITextfieldDelegate ,使用滑动键盘时应用程序崩溃。

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let text = textField.text as NSString? {
            let txtAfterUpdate = text.replacingCharacters(in: range, with: string)
            textField.text = txtAfterUpdate
        }
        return false
    }

这是苹果的错误吗?

最佳答案

我能够重现这一点 - 如果您在滑动输入期间改变 UITextField 上的文本状态 - 并且仅在滑动输入期间,它会尝试重新插入滑动的内容(即使您返回 false),这会重新触发您的委托(delegate)事件,这开始了递归循环。

这有点像黑客,但你可以用类似的东西捕获它

    private var lastEntry: String?

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.count > 1 && string == lastEntry { // implies we're swiping or pasting
            print("Caught unwanted recursion")
            return
        }
        lastEntry = string
        if let text = textField.text as NSString? {
            let txtAfterUpdate = text.replacingCharacters(in: range, with: string)
            textField.text = txtAfterUpdate
        }
        return false
    }

它会阻止用户连续两次粘贴/滑动相同的东西,但至少它会让他们在 Apple 解决问题时滑动。

关于iOS 13 崩溃与 SwipeKeyboard 和文本字段 :shouldChangeCharactersIn:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58560843/

相关文章:

ios - UIView subview 没有动画

ios - 如果图像被另一个应用程序(如照片、safari 等)复制,我如何从 UIPasteboard 获取图像的原始数据。

ios - 从带有 subview 的单个 UIView 生成多页 PDF

objective-c - 在事件 UITextField 之外的触摸上调用函数

iOS 13.0 UIMenu 和 UIContextMenuConfiguration 的 UIAction

ios 设备上的构建大小更大

iphone - 如何从 iPhone UItextField 中删除特殊字符“&”

ios - 如何更改设置为 UITextField inputView 的 UIDatePicker 的背景颜色?

objective-c - ios 13 - 带有 UISearchBar _searchField 的自定义 SearchBar 不工作

ios - Swift 5 和 iOS 13 UISearchController 错误的呈现和关闭行为