如何指定保存 SwiftUI 自定义视图的数组的类型信息 [英] How to specify the type information of an array that would hold SwiftUI custom views

查看:36
本文介绍了如何指定保存 SwiftUI 自定义视图的数组的类型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 SwiftUI,我明白要使用 SwiftUI 框架创建视图元素,您的自定义类型必须符合视图"协议.我有一个要求,我想声明一个数组,该数组将保存我将通过制作实现视图"协议的 Struct 创建的自定义 SwiftUI 组件.现在我不确定要提及什么作为数组的类型,因为提供 'View' 作为类型会导致编译器错误,因为Protocol 'View' 只能用作通用约束,因为它具有 Self或相关的类型要求".

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

推荐答案

这里有一个演示,展示了根据某些模型枚举生成不同视图的可能方法.使用 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)
                    }
            }
        }
    }
}

这篇关于如何指定保存 SwiftUI 自定义视图的数组的类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆