假设我有一个结构:
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 个元素(基于后端调用)。我想为每个元素呈现不同的 View (单击时)。目前,我正在根据我们的索引使用一个简单的 if 来执行此操作:
if self.index == 1 {
First()
} else if self.index == 2 {
Second()
} else if self.index == 3 {
Third()
} else {
First()
}
但是如果我有更多元素等,这不是最好的方法......
我的想法如下,但我不知道最好的方法是什么:
创建一个函数,根据索引返回
任何 View
,并为每个 View 指定一个默认名称,以便我可以进行迭代?例如 View1、View2 等?向我的结构添加一些特定的内容?
P.s.我也想以尽可能安全的方式做到这一点,我不想崩溃等! =)
谢谢!
最佳答案
这是 SwiftUI 2.0 中可能的方法(在 SwiftUI 1.0 中 ViewBuilder 尚不支持 switch
,因此 if/else
是唯一的方法,但您可以将其包装在枚举
也是如此)。
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
}
关于ios - 动态 View 渲染,SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63610665/