SwiftUI列出具有OnDelete和TextField绑定的ForEach

时间:2020-05-22 01:02:43

标签: swiftui swiftui-list

如何在支持onRemove()的列表上有一个绑定文本字段?

我有一个三行表。中间的行是可编辑的,Textfield绑定了一个双精度型。 我在删除行和绑定中间TextField时遇到问题

List {
            ForEach (self.model.wallet.wallet.indices, id: \.self){ i in
                HStack (alignment: .center) {
                    Text(self.model.wallet.wallet[i].ticker).frame(width: 100)

                    Spacer()
                    TextField("", value: self.$model.wallet.wallet[i].amount, formatter: self.formatter).textFieldStyle(RoundedBorderTextFieldStyle()).frame(width: 100)
                    Spacer()
                    Text(valueString(value: Float(self.model.wallet.wallet[i].holdings))).frame(width: 100)

                }
            }.onDelete { (indexSet) in
                print(indexSet)
                DispatchQueue.main.async {
                     self.model.wallet.wallet.remove(atOffsets: indexSet)
                }

            }

我无法删除此行。它崩溃了。 `致命错误:索引超出范围'

但是,如果我这样做:

List {
            ForEach (self.model.wallet.wallet, id: \.self){ coin in
                HStack (alignment: .center) {
                    Text(coin.ticker).frame(width: 100)

                    Spacer()
                    //                        TextField("1.23", value: coin.amount, formatter: self.formatter).textFieldStyle(RoundedBorderTextFieldStyle()).frame(width: 100)
                    Spacer()
                    Text(valueString(value: Float(coin.holdings))).frame(width: 100)

                }
            }.onDelete { (indexSet) in
                print(indexSet)
                DispatchQueue.main.async {
                    self.model.wallet.wallet.remove(atOffsets: indexSet)
                }

            }

我可以删除行,但是找不到绑定字段的方法。

我如何在列表上具有支持onRemove()的绑定文本字段?

针对上下文的其余代码:

 class MyCoinsViewModel : ObservableObject {
@Published var wallet : Wallet = Wallet(wallet: [])
...
}
struct MyCoinsView : View {
@ObservedObject var model = MyCoinsViewModel()
@State var isChoosing : Bool = false
var formatter : NumberFormatter {
    let formatter =  NumberFormatter()
    formatter.numberStyle = .decimal
    return formatter
}
var body : some View {
    VStack {
        Text("Add Coin")
        Button("➕", action: {
            self.isChoosing = true
        })
List { ... }
...
} 
struct CoinAmount : Codable, Hashable {
static func == (lhs: CoinAmount, rhs: CoinAmount) -> Bool {
    return lhs.hashValue == rhs.hashValue
}
var hashValue: Int {
    return (coin.symbol).hashValue
}
var coin : CryptoCoin
var holdings : Double {
    return coin.usdprice * amount
}
var ticker : String {
    return coin.symbol
}
var amount : Double
} 
struct Wallet : Codable {
var wallet : [CoinAmount]
var lastUpdated : Date? = Date.init(timeIntervalSinceNow: 0)
...
}

0 个答案:

没有答案