简体   繁体   English

SwiftUI / iOS | 在没有 NSNotification 的情况下获取键盘大小

[英]SwiftUI / iOS | Get keyboard size without NSNotification

I would like to know if it is somehow possible to get the keyboard size of the device that my application is currently running on without any notification, because I'd like to place a Button exactly at that point inside of my View where the keyboard would end.我想知道是否有可能在没有任何通知的情况下获取我的应用程序当前正在运行的设备的键盘大小,因为我想将一个 Button 恰好放在我的视图中键盘所在的那个点结尾。 There would be the possibility to change the position when the keyboard appears, but as I said before I want it to be there before it animates in.当键盘出现时有可能改变位置,但正如我之前所说,我希望它在动画进入之前就在那里。

Otherwise maybe there is any static size of the iOS keyboards, like eg 1/3 of the screen height of the device or something?否则,iOS 键盘可能有任何静态大小,例如设备屏幕高度的 1/3 之类的?

This is what I am trying to achieve:这就是我想要实现的目标:

Screenshot of hardcoded one on iPhone XS Max: iPhone XS Max 硬编码的屏幕截图:

iPhone XS Max 硬编码的屏幕截图

Thank you!谢谢!

I have done it creating an extension for Publisher.我已经为 Publisher 创建了一个扩展。 However, it uses NotificationCenter但是,它使用通知中心

extension Publishers {
    static var keyboardHeight: AnyPublisher<CGFloat, Never> {
        let willShow = NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification)
            .map { $0.keyboardHeight }
        
        let willHide = NotificationCenter.default.publisher(for: UIApplication.keyboardWillHideNotification)
            .map { _ in CGFloat(0) }
        
        return MergeMany(willShow, willHide)
            .eraseToAnyPublisher()
    }
}

Also, you need to create a state variable for keyboardHeight此外,您需要为 keyboardHeight 创建一个状态变量

@State private var keyboardHeight: CGFloat = 0

Finally, you can observe the change in height using:最后,您可以使用以下方法观察高度的变化:

Text("")
       .onReceive(Publishers.keyboardHeight) {
                            self.keyboardHeight = $0
                        }

This is the approach I used for getting the height.这是我用来获取高度的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM