iOS 15如何检测Live Text"键盘"关闭并切换至普通键盘
解决方法
一、检测Live Text键盘关闭、切换普通键盘的时机
Live Text输入模式的切换、关闭可以通过系统通知监听实现:
- 首先添加通知观察者,在控制器初始化/视图加载阶段执行:
// 监听输入模式切换(切回普通键盘触发) NotificationCenter.default.addObserver( self, selector: #selector(onInputModeChanged), name: UITextInput.currentInputModeDidChangeNotification, object: nil ) // 监听键盘隐藏(点击Live Text右上角关闭按钮触发) NotificationCenter.default.addObserver( self, selector: #selector(onKeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil )
- 实现通知回调方法,添加状态标记位判断当前是否处于Live Text模式:
// 新增私有状态标记 private var isLiveTextActive = false // 调用captureTextFromCamera时标记Live Text激活 func activateLiveText() { textField.becomeFirstResponder() textField.delegate = self isLiveTextActive = true // 激活状态标记 textField.captureTextFromCamera(textField) } @objc private func onInputModeChanged() { // 判断当前输入模式是否为Live Text let isLiveTextMode = textField.textInputMode?.identifier == "com.apple.TextInputMode.LiveText" if !isLiveTextMode && isLiveTextActive { // 已切回普通键盘,重置状态 resetLiveTextState() } } @objc private func onKeyboardWillHide() { if isLiveTextActive { // Live Text键盘关闭,重置状态 resetLiveTextState() } } private func resetLiveTextState() { isLiveTextActive = false // 按需选择是否置空代理,也可以保留代理动态调整返回值 // textField.delegate = nil }
- 在合适的时机移除通知观察者,避免内存泄漏:
deinit { NotificationCenter.default.removeObserver(self) }
二、修复文本编辑失效问题
修改shouldChangeCharactersIn代理方法的返回值逻辑,根据当前是否为Live Text模式动态返回:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let finalArray = string.components(separatedBy: " ").map({ $0.cleanString() }) if let foundedText = finalArray.first(where: { $0.count == 8 && $0.isAlphanumeric }) { textField.text = foundedText textField.endEditing(true) resetLiveTextState() textField.delegate = nil } // 动态返回:Live Text模式返回false,普通键盘模式返回true return !isLiveTextActive }
内容的提问来源于stack exchange,提问作者Vladyslav Semenchenko
相关产品推荐
相关产品推荐

