SwiftUI:删除 ForEach 中的最后一行 [英] SwiftUI: Deleting last row in ForEach
本文介绍了SwiftUI:删除 ForEach 中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试删除 ForEach
中的行.删除最后一行总是会引发索引超出范围异常.删除任何其他行不会.
I am trying to remove rows inside a ForEach
. Removing the last row always throws an index out of range exception. Removing any other row does not.
ForEach(Array(player.scores.enumerated()), id: .element) { index, score in
HStack {
if self.isEditSelected {
Button(action: {
self.player.scores.remove(at: index)
}, label: {
Image("delete")
})
}
TextField("(score)", value: self.$player.scores[index], formatter: NumberFormatter())
}
}
我尝试过使用 ForEach(player.indices...)
&ForEach(player.scores...)
,但看到同样的问题.
I have tried using ForEach(player.indices...)
& ForEach(player.scores...)
, but see the same problem.
在我看来,崩溃发生在这里self.$player.scores[index]
,因为将索引硬编码为除最后一行有效之外的任何值.
Looks to me like the crash happens here self.$player.scores[index]
, as hardcoding the index to any value other that the last row is working.
有谁知道如何解决这个问题?或者如果有更好的方法.
Does anyone know how to fix this? Or if there is a better approach.
推荐答案
这里是修复
ForEach(Array(player.scores.enumerated()), id: .element) { index, score in
HStack {
if self.isEditSelected {
Button(action: {
self.player.scores.remove(at: index)
}, label: {
Image("delete")
})
}
TextField("(score)", value: Binding( // << use proxy binding !!
get: { self.player.scores[index] },
set: { self.player.scores[index] = $0 }),
formatter: NumberFormatter())
}
}
这篇关于SwiftUI:删除 ForEach 中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文