简体   繁体   English

如何指定将包含 SwiftUI 自定义视图的数组的类型信息

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

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.我正在学习 SwiftUI 并且我明白要使用 SwiftUI 框架创建视图元素,您的自定义类型必须符合“视图”协议。 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.我有一个要求,我想声明一个数组,该数组将保存自定义 SwiftUI 组件,我将通过制作实现“视图”协议的结构来创建这些组件。 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")
    }
}

Here is a demo of possible approach to generate different views depending on some model enum.下面是根据一些 model 枚举生成不同视图的可能方法的演示。 Tested with Xcode 11.4 / iOS 13.4使用 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)
                    }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM