繁体   English   中英

动态视图渲染,SwiftUI

[英]Dynamic view rendering, SwiftUI

假设我有一个结构:

var topMenu: [TopMenu] = [TopMenu(name: "Menu", index: 1),
                      TopMenu(name: "Search", index: 2),
                      TopMenu(name: "Profile", index: 3),
                      TopMenu(name: "Settings", index: 4)]

这个结构包含一个字符串和一个索引,所以我可以创建一个基于 HStack 的菜单和一个带有这些元素的 ForEach。 这可以。 但我现在要做的是以下内容:

假设这个结构是动态的:我可以有 3 个元素,但我也可以有 5/6 个元素(基于后端调用)。 我想为每个元素呈现不同的视图(点击)。 目前,我正在根据我们的索引使用一个简单的 if 来执行此操作:

if self.index == 1 {
      First()
} else if self.index == 2 {
      Second()
} else if self.index == 3 {
      Third()
} else {
      First()
}

但是,如果我有更多元素等,这不是最好的方法......

我的想法如下,但我不知道什么是最好的方法:

  • 创建一个基于索引返回Any View的函数,并为每个视图提供一个默认名称,以便我可以迭代? 例如 View1、View2 等?

  • 向我的结构添加一些特定的东西?

Ps我也想以更安全的方式做到这一点,我不想崩溃等! =)

谢谢!

这是 SwiftUI 2.0 中的可能方法(在 SwiftUI 1.0 中 ViewBuilder 尚不支持switch ,因此if/else是唯一的方法,但您也可以将其包装在enum中)。

enum Choices: Int {
    case menu = 1
    case search = 2
    case profile = 3
    case settings = 4

    @ViewBuilder
    func view() -> some View {
        switch self {
            case menu:
                MenuView()
            case search:
                SearchView()
            case profile:
                ProfileView()
            case settings:
                SettingsView()
        }
    }
}

struct DemoChoicesUsage: View {
    @State var index = 1
    var body: some View {
        VStack {
            (Choices(rawValue: index) ?? Choices.menu).view()
        }
    }
}

此外,可选地,您还可以修改TopMenu以直接链接到枚举案例而不是索引,例如TopMenu(name: "Menu", tag: .menu)

struct TopMenu {
  let name: String
  let tag: Choices
}

暂无
暂无

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

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