ios - 在 swiftUI 上使用 ondelete 擦除多个字符串
问题描述
我正在尝试创建一个带有价格的项目列表。除了 ondelete() 函数之外,似乎一切都运行良好,我似乎无法找到一种方法来删除价格表和项目列表中的两个字符串,并且总是给我一个超出范围的致命错误。试图创建一个数字数组并将其放入 foreach 循环中,但它仍然给出了致命错误,超出范围......
@State var itemn = 0
@State var priceList : [String] = [""]
@State var itemList : [String] = [""]
@State var isEditing = false
func deleteItems(at offsets: IndexSet) {
let a = offsets.count
priceList.remove(at: a)
itemList.remove(at: a)
}
var body: some View {
GeometryReader{ res in
ZStack{
Spacer()
}.padding().background(LinearGradient(gradient: Gradient(colors: [Color(red: 0.171, green: 0.734, blue: 0.955), .white]), startPoint: .bottom, endPoint: .trailing)).background(Color(red: 0.171, green: 0.734, blue: 0.955)).edgesIgnoringSafeArea(.bottom)
ZStack{
VStack{
Form{
Section{
HStack{
Section(header: Text("To-Do List ").font(.largeTitle).fontWeight(.thin)){
Spacer()
Button(action: {
self.itemn += 1
self.itemList.append("")
self.priceList.append("")
print(self.itemList)
}, label: {
Text("Add")
})
}
}
List{
ForEach(0 ... self.itemn, id: \.self){s in
VStack{
HStack{
Text("Title: ")
TextField("Expense ", text: self.$itemList[s])
}
HStack{
Text("Price: $")
TextField("0.00", text: self.$priceList[s]).keyboardType(.decimalPad)
}
Button(action: {
self.priceList.remove(at: 0)
self.itemList.remove(at: 0)
}, label: {
Text("delete")
})
}
}.onDelete(perform: self.deleteItems)
}
}
}.onAppear {
UITableViewCell.appearance().backgroundColor = .clear
UITableView.appearance().backgroundColor = .clear
UITableView.appearance().separatorColor = .clear
}.padding()
Spacer()
}
}
}.navigationBarItems(leading: Text("To - List").font(.largeTitle).fontWeight(.thin).padding(.top))
}
}
解决方案
同步更改状态强制更新,因此您会错配两个数组。解决方案可能是使用模型项值数组而不是两个数组,例如
struct Item {
let id = UUID() // id is per-your choice
var item: String = ""
var price: String = ""
}
@State var itemList : [Item] = []
当然更新了下面的视图逻辑
推荐阅读
- google-apps-script - 为什么在第 3 行,onEdit(e) 的文件“代码”出现此错误?
- java - While 循环不退出或不显示结果
- javascript - 如何重构函数参数及其用法
- keyboard-shortcuts - ag-grid上下文菜单快捷键不起作用
- java - 无法使用 Java SDK 将文件上传到 OneDrive
- flutter - 在 Flutter/Dart 中有效解析 JSON
- python - 查找最大数字时出现 Python 错误
- c# - 如何从多个位置标签内有多个 appSettings 标签的配置文件中读取 appSettings?
- angular - 单点登录 - 跨域身份验证 (@auth0/angular2-jwt)
- c - 驱动程序开发(Windows):什么是 RTL?