问题
I am learning SwiftUI and I do understand that to create a view element using SwiftUI framework, your custom type must conform to 'View' protocol. I have a requirement where I want to declare an array which would hold custom SwiftUI components that I would be creating by making a Struct implementing the 'View' protocol. Now I am not sure what to mention as the type of the array since, providing 'View' as the type is giving the compiler error as "Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements".
struct ContentView: View {
var tabs : [View]
var body: some View {
Text("Hello World")
}
}
回答1:
Here is a demo of possible approach to generate different views depending on some model enum. Tested with Xcode 11.4 / iOS 13.4
enum CustomTabDescriptior: Int {
case one = 1
case two = 2
case three = 3
var label: String {
"\(self.rawValue).square"
}
// can be used also a function with arguments to be passed inside
// created corresponding views
var view: some View {
Group {
if self == .one {
Text("One") // << any custom view here or below
}
if self == .two {
Image(systemName: "2.square")
}
if self == .three {
Button("Three") {
print(">> activated !!")
}
}
}
}
}
struct DemoDynamicTabView: View {
let tabs: [CustomTabDescriptior] = [.one, .two, .three]
var body: some View {
TabView {
ForEach(tabs, id: \.self) { tab in
tab.view
.tabItem {
Image(systemName: tab.label)
}
}
}
}
}
来源:https://stackoverflow.com/questions/62949747/how-to-specify-the-type-information-of-an-array-that-would-hold-swiftui-custom-v