我需要在 SwiftUI 中显示折叠菜单,可以将一个 bool 值作为绑定 var 传递到子视图,但在尝试从字典传递该值时陷入困境。
参见下面的代码:
struct MenuView: View {
@EnvironmentObject var data: APIData
@State var menuCollapsed:[String: Bool] = [:]
@State var isMenuCollapsed = false;
// I am able to pass self.$isMenuCollapsed but self.$menuCollapsed[menuItem.name], why?
var body: some View {
if data.isMenuSynced {
List() {
ForEach((data.menuList?.content)!, id: \.name) { menuItem in
TopMenuRow(dataSource: menuItem, isCollapsed: self.$isMenuCollapsed)
.onTapGesture {
if menuItem.isExtendable() {
let isCollapsed = self.menuCollapsed[menuItem.name]
self.menuCollapsed.updateValue(!(isCollapsed ?? false), forKey: menuItem.name)
} else {
print("Go to link:\(menuItem.url)")
}
}
} …Run Code Online (Sandbox Code Playgroud)