Scroll to very bottom of SwiftUI Scrollview when keyboard appears

Viewed 1619

In my SwiftUI project, I have the following layout

ScrollView {
    VStack {
        Text("some text that may change while editing the stuff below")
        TextField(...)
        TextField(...)
        Button(...)
    }
}

What I would like to achieve is that whenever the TextField gets focus, the ScrollView scrolls to the very bottom, i.e. the button is visible. I tried with a wrapped UIScrollView and also keyboardWillShow-notifications, but didn't find anything that worked on both, iOS 13 and 14.

What's the best way to achieve this?

1 Answers

You can achieve this by using a ScrollViewReader, and if you don't want the onTapGesture, you can use keyboardWillShow-notifications

ScrollView {
    ScrollViewReader { value in
        VStack {
            Text("some text that may change while editing the stuff below").id(0)
            TextField(...)
                .id(1)
                .onTapGesture {
                    withAnimation() {
                        value.scrollTo(3, anchor: .top) //or if you want the button in the center use .center
                    }
                 }
            TextField(...).id(2)
            Button(...).id(3)
        }
    }
}
Related