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()
}```

Hi! To go to another view in SwiftUI, you can use NavigationStack! You also have to use NavigationLink(destination: AnotherView()) and then wrap the label in it (the Text). This way the text element becomes pressable, and when pressed, it'll take you to the next view, AnotherView()!.


struct ContentView: View {
    
    var body: some View {
        NavigationStack { //<-- Wrap your whole view into NavigationStack to enable the navigation to subviews
            ScrollView{
                VStack {
                    ForEach(0..<14) {value in
                        NavigationLink(destination: AnotherView(), label: {  //<-- Wrap your content in a NavigationLink
                            Text("Test \(value)")
                                .padding(.vertical)
                        }) //<-- Closing bracket to NavigationLink
                    }
                }
            }
        } //<-- Closing bracket to NavigationStack
    } 
}

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

The reason this doesn't work is you can't call a view from not in your view body and expect SwiftUI to show the view. The compiler throws a warning that says: "Result of AnotherView() initialiser is unused":

.onTapGesture {
    print("scrollview-item tapped")
    AnotherView() //<-- Result of AnotherView() initialiser is unused
}

Also, NavigationStack has to be used to enable navigation. Without NavigationStack and only using NavigationLink, the NavigationLink won't work.

Have a great day!

Can't call another view out of a scrollview
 
 
Q