Can't call another view out of a scrollview

Hello,

i had to found out, that I can’t call a view out of a ScrollView by tapping on an item of the scroll view. Enclosed minimal code show’s the effect. The tapping is recognized, but the view doesn’t switch to “AnotherView”.

Why is this the case? Works as designed or did I misunderstand something fundamental?

Any help appreciated.

Thx, Peter

import SwiftUI

struct ContentView: View {

    var body: some View {
        ScrollView{
            VStack {
                ForEach(0..<14) {value in
                        Text("Test \(value)")
                        .padding(.vertical)
                        .onTapGesture {
                            print("scrollview-item tapped")
                            AnotherView()
                        }
                }
            }
        }
    }
}

struct AnotherView: View {
    
    var body: some View {
        Text("Another View")
    }
}

#Preview {
    ContentView()
}

#Preview {
    AnotherView()
}

When you want to present another view the method of presenting the other view can be via a .sheet or a .fullScreenCover. In either case the sheet or fullScreenCover needs to be triggered by a Boolean value. That boolean value must be declared as a @State variable with an initial value of false which you change using maybe a Button tap or an onTapGesture in your case.

For example, this is how you would do that with a .sheet using your code as the basis.

struct ScrollViewExample: View {
    @State private var isShowingAnotherView = false

    var body: some View {
        ScrollView{
            VStack {
                ForEach(0..<14) {value in
                    Text("Test \(value)")
                        .padding(.vertical)
                        .onTapGesture {
                            print("scrollview-item tapped")
                            isShowingAnotherView = true
                        }
                }
            }
        }
        .sheet(isPresented: $isShowingAnotherView, content: {
            AnotherView()
        })
    }
}

#Preview {
    ScrollViewExample()
}

struct AnotherView: View {

    var body: some View {
        Text("Another View")
    }
}