使用该协议,KeyboardReadable
,你可以符合任何View
并从中获取键盘更新。
KeyboardReadable
协议:
import Combine
import UIKit
/// Publisher to read keyboard changes.
protocol KeyboardReadable {
var keyboardPublisher: AnyPublisher<Bool, Never> { get }
}
extension KeyboardReadable {
var keyboardPublisher: AnyPublisher<Bool, Never> {
Publishers.Merge(
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.map { _ in true },
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillHideNotification)
.map { _ in false }
)
.eraseToAnyPublisher()
}
}
它的工作原理是使用合并并创建发布者,以便我们可以接收键盘通知。
通过一个示例来了解如何应用它:
struct ContentView: View, KeyboardReadable {
@State private var text: String = ""
@State private var isKeyboardVisible = false
var body: some View {
TextField("Text", text: $text)
.onReceive(keyboardPublisher) { newIsKeyboardVisible in
print("Is keyboard visible? ", newIsKeyboardVisible)
isKeyboardVisible = newIsKeyboardVisible
}
}
}
您现在可以从isKeyboardVisible
变量来了解键盘是否可见。
当。。。的时候TextField
处于活动状态并显示键盘,打印以下内容:
键盘可见吗?真的
当按下回车键隐藏键盘时,会打印以下内容:
键盘可见吗?错误的
您可以使用keyboardWillShowNotification
/keyboardWillHideNotification
一旦键盘开始出现或消失就更新,并且keyboardDidShowNotification
/keyboardDidHideNotification
键盘出现或消失后更新的变体。我更喜欢will
变体,因为当键盘显示时更新是即时的。