edgesIgnoringSafeArea(.all) 破坏键盘响应器,SwiftUI

edgesIgnoringSafeArea(.all) breaks keyboard responder, SwiftUI

键盘响应文件如下所示:

class KeyboardResponder: ObservableObject {

    @Published var currentHeight: CGFloat = 0

    var _center: NotificationCenter

    init(center: NotificationCenter = .default) {
        _center = center
        _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    @objc func keyBoardWillShow(notification: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            withAnimation {
                currentHeight = keyboardSize.height
            }
        }
        print("the KEYBOARD HEIGHT IS \(self.currentHeight)")
    }

    @objc func keyBoardWillHide(notification: Notification) {
        withAnimation {
            currentHeight = 0
        }
        print("the KEYBOARD HEIGHT IS \(self.currentHeight)")
    }
}

我尝试在正文所在的视图中使用它:

VStack {
    VStack {
        \view content here
    }.offset(y: -self.keyboardResponder.currentHeight) \ keyboardResponder is an instance of KeyboardResponder
}.edgesIgnoringSafeArea(.all)

当我删除 edgesIgnoringSafeArea(.all) 时,它工作正常,但如果我将它放入,它会破坏偏移量,因此它根本不再移动内容...

他们在 iOS14 中弃用了 .edgesIgnoreSafeArea。新方法为要忽略的安全区域“类型”提供了多个选项:.container(通常的“安全区域”)、.keyboard(新! ) 和 .all(同时忽略容器和键盘——我怀疑这就是你得到的行为)。

改用 .ignoresSafeArea(.container)。

https://developer.apple.com/documentation/swiftui/offsetshape/ignoressafearea(_:edges:)