且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何指定保存 SwiftUI 自定义视图的数组的类型信息

更新时间:2022-11-18 20:55:05

这里有一个演示,展示了根据某些模型枚举生成不同视图的可能方法.使用 Xcode 11.4/iOS 13.4 测试

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