gpt4 book ai didi

swiftui - 在 SwiftUI 中制作聊天应用程序 : How to make ScrollView keep its place when the keyboard shows up?

转载 作者:行者123 更新时间:2023-12-03 08:34:41 30 4
gpt4 key购买 nike

我正在 SwiftUI 中制作一个聊天应用程序。这是我想要的效果:在 Telegram 或 Whatsapp 中打开任何聊天,点击输入框。当键盘向上滑动时,聊天内容也会向上滑动。因此,如果您正在查看底部消息,您仍然可以看到它。

我无法在 SwiftUI 中获得此效果。键盘向上滑动不滑动聊天内容:

import SwiftUI

struct SlidingKeyboardTest: View {
@State var inputText = "Placeholder"

var body: some View {
VStack {
ScrollView {
LazyVStack {
ForEach(1...100, id: \.self) { id in
HStack {
Spacer()
Text("message \(id)")
Spacer()
}
}
}
}
TextEditor(text: $inputText)
.frame(height: 50)
}
.background(LinearGradient(gradient: Gradient(colors: [.white, .blue, .white]), startPoint: .top, endPoint: .bottom))
.onTapGesture { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) }
}
}

struct SlidingKeyboardTest_Previews: PreviewProvider {
static var previews: some View {
SlidingKeyboardTest()
}
}

有什么想法如何实现这种效果吗?

最佳答案

您需要使用Introspect接收对 UIScrollView 的访问并监听键盘高度的变化。

这是一个代码:

import Combine
import Introspect
import SwiftUI

struct SlidingKeyboardTest: View {
@State var inputText = "Placeholder"
@State var keyboardHeight = CGFloat(0)
@State var scrollView: UIScrollView? = nil

var body: some View {
VStack {
ScrollView {
LazyVStack {
ForEach(1 ... 100, id: \.self) { id in
HStack {
Spacer()
Text("message \(id)")
Spacer()
}
}
}
}.introspectScrollView {
scrollView = $0
}
TextEditor(text: $inputText)
.frame(height: 50)
}.onReceive(Publishers.keyboardHeight) { height in
if height > 0 {
self.scrollView!.setContentOffset(CGPoint(x: 0, y: self.scrollView!.contentOffset.y + height), animated: true)
} else {
self.scrollView!.contentOffset.y = max(self.scrollView!.contentOffset.y - keyboardHeight, 0)
}

keyboardHeight = height
}

.background(LinearGradient(gradient: Gradient(colors: [.white, .blue, .white]), startPoint: .top, endPoint: .bottom))
.onTapGesture { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) }
}
}

struct SlidingKeyboardTest_Previews: PreviewProvider {
static var previews: some View {
SlidingKeyboardTest()
}
}

关于swiftui - 在 SwiftUI 中制作聊天应用程序 : How to make ScrollView keep its place when the keyboard shows up?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64289515/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com