How to specify the type information of an array that would hold SwiftUI custom views

和自甴很熟 提交于 2021-02-04 21:57:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!