如何使用ForEach中的文本字段更新结构的属性 [英] How to update attributes of a struct with TextFields made in ForEach
本文介绍了如何使用ForEach中的文本字段更新结构的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在SwiftUI中,我有一个菜单项列表,每个菜单项都有一个名称、价格等。有一堆类别,每个类别下都有一个项目列表。
struct ItemList: Identifiable, Codable {
var id: Int
var name: String
var picture: String
var list: [Item]
@State var newItemName: String
}
我正在寻找一种方法,以便在每个类别内创建一个Textfield,以添加到其项目数组中。
通过ForEach循环创建TextFields非常简单,但我在尝试使用输入的文本将新项添加到正确的类别时遇到了困难。
ForEach(menu.indices) { i in
Section(header: Text(menu[i].name)) {
ForEach(menu[i].list) { item in
Text(item.name)
}
TextField("New Type:", text: /*some kind of bindable here?*/) {
menu[i].list.append(Item(name: /*the text entered above*/))
}
}
}
我考虑过像this other question那样使用@发布和可观察的对象,但我需要ItemList是一个可编码的结构,所以我不知道如何将答案与我的案例相匹配。
TextField("New Type:", text: menu[i].$newItemName)
不管怎样,任何想法都将不胜感激,谢谢!
推荐答案
您只需集中View
。
import SwiftUI
struct ExpandingMenuView: View {
@State var menu: [ItemList] = [
ItemList(name: "Milk Tea", picture: "", list: [ItemModel(name: "Classic Milk Tea"), ItemModel(name: "Taro milk tea")]),
ItemList(name: "Tea", picture: "", list: [ItemModel(name: "Black Tea"), ItemModel(name: "Green tea")]),
ItemList(name: "Coffee", picture: "", list: [])
]
var body: some View {
List{
//This particular setup is for iOS15+
ForEach($menu) { $itemList in
ItemListView(itemList: $itemList)
}
}
}
}
struct ItemListView: View {
@Binding var itemList: ItemList
@State var newItemName: String = ""
var body: some View {
Section(header: Text(itemList.name)) {
ForEach(itemList.list) { item in
Text(item.name)
}
TextField("New Type:", text: $newItemName, onCommit: {
//When the user commits add to array and clear the new item variable
itemList.list.append(ItemModel(name: newItemName))
newItemName = ""
})
}
}
}
struct ItemList: Identifiable, Codable {
var id: UUID = UUID()
var name: String
var picture: String
var list: [ItemModel]
//@State is ONLY for SwiftUI Views
//@State var newItemName: String
}
struct ItemModel: Identifiable, Codable {
var id: UUID = UUID()
var name: String
}
struct ExpandingMenuView_Previews: PreviewProvider {
static var previews: some View {
ExpandingMenuView()
}
}
如果您不使用Xcode13和iOS 15+,那么在SO中有很多绑定数组元素的解决方案。以下只是其中之一
ForEach(menu) { itemList in
let proxy = Binding(get: {itemList}, set: { new in
let idx = menu.firstIndex(where: {
$0.id == itemList.id
})!
menu[idx] = new
})
ItemListView(itemList: proxy)
}
还请注意,使用indices
被认为是不安全的。您可以从WWDC2021观看揭开SwiftUI的神秘面纱以了解更多详细信息。
这篇关于如何使用ForEach中的文本字段更新结构的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文