如何检测swiftui中是否存在键盘

我想知道按下按钮时键盘是否存在。我该怎么做?我试过了,但我没有任何运气。谢谢。

回答

使用此协议,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()
    }
}

它的工作原理是使用 Combine 并创建一个发布者,以便我们可以接收键盘通知。

通过如何应用它的示例视图:

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变体,因为当键盘显示时更新是即时的。


以上是如何检测swiftui中是否存在键盘的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>