SwiftUI中如何将滑动项的索引传递给swipeActions按钮的函数?
问题解决:SwiftUI列表滑动操作传递索引值
你的问题核心是滑动操作的作用域不对:你把.swipeActions加在了ForEach的外层,导致闭包里访问不到循环中的index变量,编译器才抛出类型转换的错误。
修正步骤:
- 将
.swipeActions从ForEach的末尾移到ForEach内部的列表项视图(也就是Text)后面,这样闭包就能直接捕获当前循环的index和match。 - 建议把全局的
savedMatches改成@State变量,这样后续修改数组时列表能自动刷新(原代码里的全局变量做不到响应式更新)。
修正后的完整代码:
import SwiftUI struct Match: Hashable, Codable, Identifiable { var homeTeam: String var id = UUID() } struct ContentView: View { // 用@State修饰数组,实现响应式更新 @State private var savedMatches = [ Match(homeTeam: "discourge") ] var body: some View { VStack{ List{ ForEach(Array(zip(savedMatches.indices, savedMatches)), id: \.0) { index, match in Text("\(index): \(match.homeTeam)") // 将swipeActions移到这里,作用域内可直接访问index .swipeActions{ Button(role: .destructive, action: { cleanUp(item: index) // 可选:如果要删除对应项,添加下面一行 savedMatches.remove(at: index) }, label: { Label("Clean Up", systemImage: "gear") }) } } } } } func cleanUp(item: Int) { print("the item swiped has an index of \(item)") } }
关键说明:
- 原代码中
.swipeActions是给整个ForEach返回的列表组加滑动操作,而不是单个列表项,所以闭包无法获取循环中的index。 - 移到内部后,每个列表项都有自己的滑动操作,闭包能直接捕获当前循环的
index,自然就能传递给cleanUp函数。
内容的提问来源于stack exchange,提问作者user19545625
相关产品推荐
相关产品推荐

