因此,我有一个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)")
}
}
在其他视图中,我创建一个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)
}
}
}
在放下Xcode 12 / SwiftUI 2之前,这就像是一种魅力,但是我认为它们随着视图刷新的方式发生了变化-任何人都知道它们发生了什么变化以及这里是否可以解决我的问题?
编辑:在我看来,如果我删除edgesIgnoringSafeArea(.all),它可以正常工作,但是很奇怪。本质上,视图只能向上移动到所有视图都在框架中的位置,它不允许整个视图向上移动(并移出屏幕视图)...我将使用一个vid来显示我的意思是...
这是当更多元素占据屏幕大部分(因此偏移量非常小)时的链接
这是元素较少时的链接,因此偏移量变得更大
如果GeometryReader封装了视图,则实际上是将其中断并使其完全停止响应。如果我将其删除,则它会根据需要运行...
答案 0 :(得分:3)
从最新的Swift,Xcode 12和iOS14开始,我注意到它是标准内置的,当键入时文本字段不可见时。屏幕随键盘高度上升,并显示原始字段。例如,使用可滚动视图和20个文本字段进行尝试。
也许您可以摆脱observableheight
的情况,而无需对其进行硬编码。