0

I tried to add a navigation view in the list as following. But it not works saying Result of 'NavigationView<Content>' initializer is unused

var body: some View {
    GeometryReader { geometry in
        VStack {
            List {
                ForEach(self.allItems){ item in
                    TaskRow(item: item)
                    .onTapGesture {
                        // TODO: switch to another view                       
                        NavigationView {
                            VStack {
                                Text("Hello World")
                                NavigationLink(destination: AnotherView()) {
                                    Text("Do Something")
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

And AnotherView is a SwiftUI file as following:

import SwiftUI

struct AnotherView: View {
    var body: some View {
        VStack{
            Text("Hello, World!")
        }
    }
}

struct AnotherView_Previews: PreviewProvider {
    static var previews: some View {
        AnotherView()
    }
}

I have tried the solution in stackoverflow Switching Views With Observable Objects in SwiftUI and SwiftUI Change View with Button. They neither work in my situation.

How to switch to another view by onTapGesture of the list in SwiftUI like following:

var body: some View {
    GeometryReader { geometry in
        VStack {
            List {
                ForEach(self.allItems){ item in
                    TaskRow(item: item)
                    .onTapGesture {
                        // TODO: switch to another view                       
                        AnotherView()
                    }
                }
            }
        }
    }
}
George
  • 25,988
  • 10
  • 79
  • 133
Muz
  • 699
  • 1
  • 11
  • 25

1 Answers1

2

You have to place whole your body into NavigationView.

Example

struct Item: Identifiable {
  let id = UUID()
  let name: String
}

struct ContentView: View {
  var body: some View {
    NavigationView {
      List {
        ForEach([Item(name: "A"), Item(name: "B")]) { value in
          NavigationLink(destination: X(item: value)) {
            Text(value.name)
          }
        }
      }
    }
  }
}

struct X: View {
  let item: Item

  var body: some View {
    Text(item.name)
  }
}
dimpiax
  • 12,093
  • 5
  • 62
  • 45