如何根据某个标签值return不同的视图?

How to return different views based on a certain tag value?

我正在尝试从视图对象数组中 return .sheet 修饰符中的视图。我无法获取为不同视图设置标签的 SwiftUI 逻辑。这可能是非常简单的事情,但我无法弄清楚。

我已经尝试过 if 语句和带有 switch/case 的函数,但我无法 return 特定视图。我相信,因为我手动向对象添加了一个 tag,一旦满足条件,它 return 在所有按钮中只有一个视图 (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)

]

我希望能够 return 剩余的 Destination View2, 3, and 4 用于其他按钮。

我会尝试使用循环的 .sheet 声明,否则你会得到很多 .sheet "objects" 都是由同一个 [=14 触发的=] 并且很可能只会渲染第一个。

所以,我认为这会奏效:

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

这是一个显示工作示例的工作 playground:

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