[SwiftUI] How to implement natural TextField's keyboard avoidance in ScrollView?

"What I wanted to achieve was that when the keyboard appears, the scroll view should be aware of the position and scroll to that specific position (so users can see the same content even if the keyboard pops up, similar to WhatsApp or other chat apps that maintain scroll position while typing a new message).

I've found only one solution! Rotate the inner content of the scroll view by 180 degrees. Then rotate the entire scroll view by 180 degrees again.

ScrollView {
 LazyVStack() {
  ForEach(comments) { comment in
 .rotationEffect(.degrees(180)).scaleEffect(x: -1, y: 1, anchor: .center)
.rotationEffect(.degrees(180)).scaleEffect(x: -1, y: 1, anchor: .center)

While this approach allows the scroll view to keep growing into the top area, it also has side effects.

I noticed some new API for ScrollView in iOS 17, but currently, I'm developing for iOS 16, so I need another approach.

If I use UIKit's TableView and wrap it with UIViewRepresentable, it was possible to maintain the scroll view's position too.

Is there a way to implement this only using SwiftUI?

This forum is meant for Swift language questions, for frameworks like SwiftUI you'll probably have better luck getting an answer if you ask on stackoverflow or the Apple developer forums.

That said I did something similar awhile ago. I only needed to keep focusable elements visible when the keyboard popped up though, so it may not work for you. I basically just listened for the keyboard willAppear notification and captured the currently focused element, then in the keyboards didAppear notification called the ScrollView's scrollTo to make it visible.

Thanks for the reply.
I didn't know it was only for the swift language question haha

1 Like