键盘偏移在 SwiftUI 2 中不再起作用

nic*_*ing 5 keyboard xcode offset swift swiftui

所以我有一个 ObservableObject 将发布的变量“currentHeight”设置为键盘的高度:

import Foundation
import 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)")
}
}
Run Code Online (Sandbox Code Playgroud)

在我的其他视图中,我创建一个 ObservedObject KeyboardResponder ,然后在视图主体内,我将有一些设置垂直偏移的视图:

struct ViewName: View {
    @ObservedObject var keyboardResponder = KeyboardResponder()
    var body: some View {
        GeometryReader { proxy in 
            VStack {
                Text("this should be offset")
                .offset(y: -keyboardResponder.currentHeight)
            }.edgesIgnoringSafeArea(.all)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Xcode 12/SwiftUI 2 下降之前,这就像一个魅力,但我认为他们改变了视图刷新方式——任何人都知道他们改变了什么,以及我的问题是否有解决方案?

编辑:在我看来,如果我删除 EdgeIgnoringSafeArea(.all),它有点有效,但很奇怪。本质上,视图只能向上移动到所有视图都在框架中的位置,它不允许整个视图向上移动(并移出屏幕视图)......我将添加一个视频来展示什么我是说...

这是当有更多元素占据大部分屏幕时的链接(因此偏移量非常小)

https://youtu.be/jpID11-rZDs

这是当元素较少时的链接,因此偏移量会变得更大

https://youtu.be/MjqX1qDEA6E

如果 GeometryReader 封闭了视图,那么这才是真正破坏它并阻止它响应的原因。如果我删除它,那么它就会根据需要运行......

Fab*_* H. 3

从最新的 Swift、Xcode 12 和 iOS14 开始,我注意到它是标准内置的,打字时文本字段不可见。屏幕随着键盘高度升高并显示原始字段。例如,尝试使用可滚动视图和 20 个文本字段。也许你可以摆脱你的observableheight并做到这一点,而无需对其进行硬编码。

在此输入图像描述