I'm currently working on a SwiftUI project and facing an issue with the ScrollView component. Specifically, I'm trying to implement functionality similar to WhatsApp or Telegram chat, where the content of the ScrollView moves up when the keyboard appears.
Below is a simplified example of what I'm trying to achieve:
ZStack {
ScrollViewReader { value in
Button ("Move to #8") {
withAnimation {
value.scrollTo(8)
selectedIndex = 8
}
}
ScrollView(.vertical, showsIndicators: false) {
LazyVStack(spacing: 10) {
ForEach(0...50, id: \.self) { index in
Text("Item \(index)")
.font(.title)
.foregroundStyle(.white)
.frame(width: height(index: index), height: height(index: index)) // frame for selected
.background(colors[index % colors.count])
.cornerRadius(8)
.id(index)
}
}
}
.padding(.bottom, 50)
}
VStack {
TextField("Message", text: $fullText)
}
.padding(.horizontal)
.frame(maxHeight: .infinity, alignment: .bottom)
}
In this example, I'm manually scrolling to a specific position using ScrollViewReader. However, my goal is for the last visible text to automatically move above the keyboard when it appears, and return to its original position when the keyboard disappears.
I've noticed that many developers encounter similar challenges with SwiftUI. If anyone has successfully implemented this behavior or has insights on how to achieve it, I would greatly appreciate your help.
I recently did this by
This is a quick implementation I did for your question, there's a lot to clean up but hopefully it still helps
For the KeyboardObserver