SwiftUI ScrollView键盘回避



首先。我知道SwiftUI ScrollView有限制。我希望能在这里解决这个问题。

我的问题是我有一个聊天框…一个带有ScrollView和文本输入的VStack。我能够得到文本输入是键盘自适应…即。当你输入时,它会随着键盘向上移动。

问题是ScrollView失去了它的滚动位置。所以,如果你滚动到底部然后激活键盘…你再也看不到底部了。它几乎像一个ZStack。

我想要的是模仿相同的行为,WhatsApp保持滚动位置,同时输入一个新的消息。

我知道关于ScrollViewReader和scrollTo…在这种情况下,这似乎是一个黑客,我希望避免它。如果有的话,也许有一个布局相关的修复?

幸运的是,我能够通过将.keyboardAdaptive()添加到ScrollView文本输入以及从padding更改为offset

来解决这个问题。
struct KeyboardAdaptive: ViewModifier {
@State private var keyboardHeight: CGFloat = 0
@State var offset: CGFloat

func body(content: Content) -> some View {
content
.offset(y: -keyboardHeight)
.onReceive(Publishers.keyboardHeight) {
self.keyboardHeight = $0 == 0 ? 0 : $0 - offset
}
}
}

也许是更好的选择。如果你使用的是带有scrollview的iOS 14+,或者你可以选择使用scrollview

https://developer.apple.com/documentation/swiftui/scrollviewproxyhttps://developer.apple.com/documentation/swiftui/scrollviewreader

下面可能有帮助

ScrollViewReader { (proxy: ScrollViewProxy) in
ScrollView {
view1().frame(height: 200)
view2().frame(height: 200)
view3() <-----this has textfields 
.onTapGesture {
proxy.scrollTo(1, anchor: .center)
}
.id(1)
view4() <-----this has text editor
.onTapGesture {
proxy.scrollTo(2, anchor: .center)
}
.id(2)
view5().frame(height: 200)
view6().frame(height: 200)
submtButton().frame(height: 200)
}
}

anyView().onTapGesture {
proxy.scrollTo(_ID, anchor: .center)
}.id(_ID)

希望这能帮助到一些人:)

最新更新