Menu Swiftui动态更新菜单组件列表

Menu Swiftui动态更新菜单组件列表,menu,swiftui,Menu,Swiftui,我有两个菜单组件,需要在第一个菜单组件中进行选择后更新第二个菜单中的元素数量。下面是一个简化的示例代码: import SwiftUI struct ContentView: View { @State var menu1List: [Int] @State var menu2List: [String] @State var currentIndex: Int init() { _menu1List = State(init

我有两个菜单组件,需要在第一个菜单组件中进行选择后更新第二个菜单中的元素数量。下面是一个简化的示例代码:

import SwiftUI

struct ContentView: View {
    
    @State var menu1List: [Int]
    @State var menu2List: [String]
    @State var currentIndex: Int
    
    init() {
        _menu1List = State(initialValue: [1, 2, 3, 4, 5, 6 , 7, 8])
        _menu2List = State(initialValue: ["A", "B", "C", "D", "E", "F", "G", "H"])
        _currentIndex = State(initialValue: 0)
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            MenuView(menu1List: $menu1List, menu2List: $menu2List, currentIndex: $currentIndex)
            ForEach(menu2List.indices) { index in
                Text("Item \(menu2List[index])") \\Menu 1 selection in MenuView causes index out of range exception.
            }
            Spacer()
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct MenuView : View {
    
    @Binding var menu1List: [Int]
    @Binding var menu2List: [String]
    @Binding var currentIndex: Int

    var body: some View {
        HStack {
            Menu {
                ForEach(menu1List.indices) { index in
                    Button(action: {
                        menu2List = ["A", "B", "C", "D"]
                    }
                    ) {
                        Text("\(menu1List[index])")
                    }
                }
            } label: {
                Text("Menu1")
                Image(systemName: "chevron.down.circle")
            }
            
            Spacer()

            Menu {
                ForEach(menu2List.indices) { index in
                    Button(action: {
                        currentIndex = index
                    }
                    ) {
                        Text("\(menu2List[index])")
                    }
                }
            } label: {
                Text("Menu2")
                Image(systemName: "chevron.down.circle")
            }
        }
        .padding()
    }
}

当我降低菜单2中元素的数量时,我会得到一个索引超出范围的异常,如代码所示。有办法解决这个问题吗?我将非常感谢您在这方面提供的任何帮助。

您使用了
ForEach
构造函数的静态变量(即预期数据不会更改),但如果您想更改
ForEach
的内容,则必须使用动态变量(id为
id:


ForEach(menu2List.index,id:\.self){index in//工作得非常出色!还感谢您解释静态和动态ForEach之间的差异。
    ForEach(menu2List.indices, id: \.self) { index in    // << here !!
        Text("Item \(menu2List[index])")
    }