swiftui - 使用 SwiftUI 的列表内的多个 NavigationLink
问题描述
我试图NavigationLink
在一个结构中有两个 s ,我将其用作NavigationLink
一个List
withForEach
但是代码不起作用(导航也不会发生View
),这里是代码:
struct mainView : View {
@State var people = [Person(name: "one", family: "1", type: "men"),Person(name: "two", family: "2", type: "women")]
var body : some View {
List{
ForEach(self.people, id:\.self){person in
NavigationLink(destination: Text("hi")) {
PersonView(person : person)
}.buttonStyle(BorderlessButtonStyle())
}
}
}
struct Person {
var name : String
var family : String
var type : String
}
struct PersonView : View {
@State var person : Person?
var body : some View {
HStack{
NavigationLink(destination: Text(self.person.name)) {
Text("this is \(self.person.name) \(self.person.family)")
}
NavigationLink(destination: Text(self.person.type)) {
Text(self.person.type)
}
}
}
}
我.buttonStyle
在阅读后添加了它可能会有所帮助,但它什么也没做。我还尝试了以下 PersonView :
struct PersonView : View {
@State var person : Person?
@State var goToFirst = false
@State var goToType = false
var body : some View {
VStack{
Button(action:{
self.goToFirst.toggle()
}){
Text("this is \(self.person.name) \(self.person.family)")
}.buttonStyle(BorderlessButtonStyle())
Button(action:{
self.goToType.toggle()
}){
Text(self.person.type)
}.buttonStyle(BorderlessButtonStyle())
NavigationLink(destination: Text(self.person.name), isActive : self.$goToFirst) {
Text("").frame(width: 0.01, height: 0.01)
}
NavigationLink(destination: Text(self.person.type), isActive : self.$goToType) {
Text("").frame(width: 0.01, height: 0.01)
}
}
}
这也不起作用,当我单击它将导航到的单元格上的任意位置时,我应该怎么做,当我Text("hi")
单击相应的区域时,它将导航到正确的View
.
重要提示:这个视图是从一个用 a 包裹的视图导航到的NavigationView
解决方案
您还没有添加导航视图,这就是问题所在。
struct MainView: View {
@State private var peoples = [Person(name: "one", family: "1", type: "men"),Person(name: "two", family: "2", type: "women")]
var body: some View {
NavigationView { //This is important
List {
ForEach(self.peoples, id: \.name) { people in
NavigationLink(destination: PersonView(person: people)) {
Text(people.name)
}
}
}
.navigationTitle("Demo")
}
}
}
struct Person {
var name : String
var family : String
var type : String
}
struct PersonView : View {
@State var person : Person?
var body : some View {
HStack{
NavigationLink(destination: Text(self.person.name)) {
Text("this is \(self.person.name) \(self.person.family)")
}
NavigationLink(destination: Text(self.person.type)) {
Text(self.person.type)
}
}
}
}
推荐阅读
- mercurial - 防止使用钩子拉树枝
- python - 如何在两个 Python 类之间共享一个变量?
- javascript - 动态创建一个 bootstrap-4 行并将 div 附加到它
- c - C语言游戏的while循环?
- .net-core - ConfigureWebHostDefaults 和 ConfigureWebHost 方法有什么区别?
- html - 标签不可点击且未链接
- html - CSS覆盖定位问题
- javascript - 如何在 chrome 扩展程序中重新定向到谷歌搜索?
- excel - 从包含 CSV 文件的文件夹中筛选 Power Query 中的多个条件的方法
- vuejs2 - vue-router 在 url 中返回 'function%20%' 而不是 param