Swift - 如何在菜单中选择按钮时获取索引
Swift - How to get the index when a button is selected in a menu
我做了一个带按钮的菜单。选择按钮后,我想将所选按钮的索引传递给函数以进行计算。我能够获取所选按钮的值,但无法获取索引值。我是 Swift 的新手,此时卡住了。一定是一件容易的事情,但还找不到解决方案。见下图:
在下面的代码中,我想在以下语句中传递索引(整数):
ContentView.displayDate = myPict.myFirstDayMonth (maand: gekozenMaand)
代码:
let hoofdstukTabel = [" 1 - Impact", " 2 - Change", " 3 - Portfolio", " 4 - Innovation", " 5 - Analysis", " 6 - Digital", " 7 - Effectiveness", " 8 - Sport & Fun", " 9 - Strategy", "10 - Structure", "11 - Value", "12 - Management"]
var body: some View {
VStack {
Menu {
ForEach(hoofdstukTabel, id: \.self) { action in
Button(action) {
let gekozenMaand = "\(action)"
ContentView.displayDate = myPict.myFirstDayMonth (maand: gekozenMaand)
curDate = myPict.myPicture()
}
}
} label: {
Label(myPict.myChapter(), systemImage: "diamond")
.font(.footnote)
.foregroundColor(Color.gray)
}
您可以使用枚举序列来获取每个元素的索引和字符串。
ForEach(Array(hoofdstukTabel.enumerated()), id: \.1) { index, action in
// your content
}
我做了一个带按钮的菜单。选择按钮后,我想将所选按钮的索引传递给函数以进行计算。我能够获取所选按钮的值,但无法获取索引值。我是 Swift 的新手,此时卡住了。一定是一件容易的事情,但还找不到解决方案。见下图:
在下面的代码中,我想在以下语句中传递索引(整数):
ContentView.displayDate = myPict.myFirstDayMonth (maand: gekozenMaand)
代码:
let hoofdstukTabel = [" 1 - Impact", " 2 - Change", " 3 - Portfolio", " 4 - Innovation", " 5 - Analysis", " 6 - Digital", " 7 - Effectiveness", " 8 - Sport & Fun", " 9 - Strategy", "10 - Structure", "11 - Value", "12 - Management"]
var body: some View {
VStack {
Menu {
ForEach(hoofdstukTabel, id: \.self) { action in
Button(action) {
let gekozenMaand = "\(action)"
ContentView.displayDate = myPict.myFirstDayMonth (maand: gekozenMaand)
curDate = myPict.myPicture()
}
}
} label: {
Label(myPict.myChapter(), systemImage: "diamond")
.font(.footnote)
.foregroundColor(Color.gray)
}
您可以使用枚举序列来获取每个元素的索引和字符串。
ForEach(Array(hoofdstukTabel.enumerated()), id: \.1) { index, action in
// your content
}