[英]Swiftui foreach index out of range ondelete issue
我遇到了這個問題,onDelete 在一個視圖中工作,但是當我做同樣的事情時它在不同的視圖中不起作用。
在第一個視圖中,它創建了一個空數組。
@State var funds: [Account.Fund] = []
當用戶創建基金時,它會使用 ForEach 將它們打印到列表中。
if funds.count > 0{
ForEach(funds.indices, id: \.self) { index in
StandardRowView(word: funds[index].name, number: funds[index].balance)
}
.onDelete(perform: { indexSet in
funds.remove(atOffsets: indexSet)
})
}
這工作正常。 當我滑動並按刪除時,它將刪除而沒有任何問題。 但是,要創建基金,用戶必須 go 以不同的視圖。 該“資金”變量被傳遞。
NavigationLink(
destination: AddFundView(funds: $funds, savingsBalance: $balance),
label: {
Text("Funds")
})
在 AddFundView 中,它是一個綁定。
@Binding var funds: [Account.Fund]
現在在 AddFundView 中,它會在用戶添加它們時將它們打印到列表中。 該代碼與以前相似,但它確實有一些額外的東西,因此他們可以編輯輸入的金額。
ForEach(funds.indices, id: \.self) { index in
//StandardRowView(word: funds[index].name, number: funds[index].balance)
HStack{
Text(funds[index].name)
Spacer()
TextField("Amount", value: $funds[index].balance, formatter: NumberFormatter.currency)
.keyboardType(.numbersAndPunctuation)
.multilineTextAlignment(.trailing)
.onChange(of: funds[index].balance, perform: { value in
//Resets the fund balance if it exceeds the savings balance
if value > savingsBalance || fundsTotal > savingsBalance{
funds[index].balance = copy[index].balance
}
})
}
}
.onDelete(perform: { indexSet in
funds.remove(atOffsets: indexSet)
})
當您在 AddFundView 中使用 onDelete 時,我收到此錯誤。
Swift/ContiguousArrayBuffer.swift:580: Fatal error: Index out of range
2021-04-23 20:06:56.400433-0400 WMMG[12180:9619685] Swift/ContiguousArrayBuffer.swift:580: Fatal error: Index out of range
我有點困惑,因為同樣的行為也在應用程序的其他地方發生。 我已經看過一些關於此的先前問題和答案,它提到它與使用“索引”有關。 但是,它在使用它時有效,只是由於某種我不理解的原因並非每次都有效。 任何人都可以幫我解決這個問題嗎?
更新:它似乎與 TextField 有關。 如果我評論它,它工作正常。 我相信這與TextField的這一部分有關。 我不確定如何獲得我想要的行為。
value: $funds[index].balance
ForEach 將每個項目作為索引返回(來自'index in'),您可以使用該項目而不是訪問數組中的該項目。 您只需要將資金數組本身傳遞給 ForEach。
我對復制部分有點困惑,但試試這個:
ForEach(funds, id: \.self) { index in
//StandardRowView(word: index.name, number: index.balance)
HStack{
Text(index.name)
Spacer()
TextField("Amount", value: $index.balance, formatted: NumberFormatter.currency)
.keyboardType(.numbersAndPunctuation)
.multilineTextAlignment(.trailing)
.onChange(of: index.balance, perform: { value in
//Resets the fund balance if it exceeds the savings balance
if value > savingsBalance || fundsTotal > savingsBalance{
index.balance = copy[index].balance // not sure here
}
})
}
}
.onDelete(perform: { indexSet in
funds.remove(atOffsets: indexSet)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.