我想一个内返回视图.sheet
修改,从视图对象的数组。 我遇到麻烦SwiftUI逻辑对于不同的看法设置标签。 这可能是很简单的东西,但我不能图出来。
if语句我已经尝试过了,并与开关/箱的功能,但我无法返回一个特定视图。 我相信,因为我已经添加了一个tag
手动对象,一旦条件满足,它只返回一个单一的视图( Destination View1
中的所有按钮)。
这是我ForEach
对数组环covers
:
var covers = coverData
ForEach(covers) { item in
Button(action: { self.isPresented.toggle() }) {
CoverAttributes(title: item.title,
alternativeTitle: alternativeTitle,
tapForMore: item.tapForMore,
color: item.color,
shadowColor: item.shadowColor)
.sheet(isPresented: self.$isPresented, content: { Text("Destination View1") })
}
}
该阵列的结构是这样的:
let coverData = [
Cover(title: "Title1",
alternativeTitle: "Alternative title",
tapForMore: "Tap to see",
color: Color("background3"),
shadowColor: Color("backgroundShadow3"),
tag: 1)
// Three more items with tags 2, 3, 4)
]
我希望能够归还剩余Destination View2, 3, and 4
的其他按钮也是如此。
我会尝试采取.sheet
声明循环的我们,否则你会拥有很多.sheet
“对象”由同一个触发$isPresented
和最有可能第一个只会被渲染。
所以,我认为,这将工作:
var covers = coverData
var selectedTag = 0
Group {
ForEach(covers) { item in
Button(action: {
self.selectedTag = item.tag
self.isPresented.toggle()
}) {
CoverAttributes(
title: item.title,
alternativeTitle: alternativeTitle,
tapForMore: item.tapForMore,
color: item.color,
shadowColor: item.shadowColor)
}
}
}
.sheet(isPresented: self.$isPresented, content: {
Text("Destination View \(self.selectedTag)")
// Here you could use a switch statement on selectedTag if you want
})
这里显示的工作示例工作操场:
import SwiftUI
import PlaygroundSupport
struct Cover {
var tag: Int
var title: String
}
struct ContentView : View {
@State var isPresented = false
@State var selectedTag = 0
var covers = [
Cover(tag: 1, title: "Cover 1"),
Cover(tag: 2, title: "Cover 2"),
Cover(tag: 3, title: "Cover 3")
]
var body: some View {
Group {
ForEach(covers, id: \.tag) { item in
Button(action: {
self.selectedTag = item.tag
self.isPresented.toggle()
}) {
Text(item.title)
}
}
}
.sheet(isPresented: self.$isPresented, content: {
if self.selectedTag == 1 {
Text("Tag 1")
} else if self.selectedTag == 2 {
Text("Tag 2")
} else {
Text("Other tag")
}
})
}
}
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())