【发布时间】:2020-07-26 01:18:59
【问题描述】:
我有一个使用 SwiftUI List 显示的菜单。下图示例:
我想要做的是将 NavigationLink 与不同的目标视图一起使用。我尝试在 List 块中使用 switch 语句,但 Xcode 抛出错误:
Closure containing control flow statement cannot be used with function builder 'ViewBuilder'
下面是我的代码:
struct HomeView: View {
enum MenuItem: String, CaseIterable, Identifiable {
var id : MenuItem {
self
}
case firstCase = "Staff"
case secondCase = "Projects"
case thirdCase = "Invoices"
}
var body: some View {
NavigationView {
List(MenuItem.allCases) { itemText in
switch itemText {
case .firstCase:
NavigationLink(destination: StaffDetail()) {
HomeMenuRow(itemText: itemText)
}
break
case .secondCase:
NavigationLink(destination: ProjectsDetail()) {
HomeMenuRow(itemText: itemText)
}
break
case .thirdCase:
NavigationLink(destination: InvoicesDetail()) {
HomeMenuRow(itemText: itemText)
}
break
}
}
.navigationBarTitle(Text("Menu"))
}
}
}
似乎找到了一些解决方案here,但不确定如何在List 对象中使用它。
【问题讨论】:
-
看起来我发现我需要通过内部工厂方法函数调用此类代码。我说的对吗?
-
您需要将您的逻辑移到
body之外,然后调用一个函数,然后返回您需要的内容。