Prevent SwiftUI ScrollView from scrolling to active TextField when returning from NavigationLink

Viewed 197

When a SwiftUI TextField in a ScrollView is active, tapping on (and returning from) a NavigationLink in the ScrollView will cause the ScrollView to scroll to the active TextField. If the TextField is not active, the scroll position is maintained.

Is there a way to maintain the scroll position regardless of the state of the TextField?

The following code exhibits my problem in iOS 14 (14.6), Swift 5 (5.4).

struct Num: View {
    let num: Int
    var body: some View {
        Text(String(num))
    }
}

struct Main: View {
    @State private var input = ""
    
    var body: some View {
        NavigationView {
            ScrollView {
                HStack {
                    TextField("Input", text: $input)
                    Button("Cancel", action: {
                        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                    })
                }
                ForEach(0 ..< 100, id: \.self) { num in
                    NavigationLink(
                        destination: Num(num: num),
                        label: {
                            Text(String(num))
                        }
                    )
                }
            }
        }
    }
}
0 Answers
Related