我想知道是否有任何本地键盘当前输入使用
UITextInputMode.activeInputModes
来检查当前的键盘语言。我正在用这种方式来做。但它只检测一次语言,当你快速键盘时,值总是true
class KeyboardHandler: ObservableObject {
@Published var isAr = false
init() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func keyboardWillChange(_ notification: Notification) {
if let inputMode = UITextInputMode.activeInputModes.first(where: { $0.primaryLanguage == "ar" }) {
let lang = inputMode.primaryLanguage
isAr = lang == "ar"
print(isAr)
}
}
}
在我的 SwiftUI 中,我使用这个接收通知:
.onReceive(keyboardHandler.$isAr) { isAr in
print(isAr)
}
任何帮助将不胜感激
您需要将通知对象转换为 UITextInputMode 并检查它的激活语言。
@objc private func keyboardWillChange(_ notification: Notification) {
guard let inputMode = notification.object as? UITextInputMode,
let lang = inputMode.primaryLanguage else { return }
isAr = lang == "ar"
print(isAr)
}