如何通过SwiftUI中列表的每个元素的onTapGesture切换到另一个视图?

时间:2020-04-25 13:45:05

标签: ios swift swiftui

我尝试在列表中添加导航视图,如下所示。但是说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")
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

AnotherView是一个SwiftUI文件,如下所示:

import SwiftUI

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

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

我尝试了stackoverflow Switching Views With Observable Objects in SwiftUISwiftUI Change View with Button中的解决方案。他们都不适合我的情况。

如何通过SwiftUI中列表的onTapGesture切换到另一个视图,如下所示:

var body: some View {
    GeometryReader { geometry in
        VStack {
            List {
                ForEach(self.allItems){ item in
                    TaskRow(item: item)
                    .onTapGesture {
                        // TODO: switch to another view                       
                        AnotherView()
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您必须将整个身体放入NavigationView

示例

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