【问题标题】:Persistently store list items added by user in SwiftUI持久存储用户在 SwiftUI 中添加的列表项
【发布时间】:2022-06-15 01:08:24
【问题描述】:

我对 swift 非常陌生(就像我今天开始的那样),我有允许用户将项目添加到列表的代码:

private func onAdd() {
    let alert = UIAlertController(title: "Enter a name for your plant", message: "Make sure it's descriptive!", preferredStyle: .alert)
       alert.addTextField { (textField) in
           textField.placeholder = "Enter here"
       }
    alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in
        let textField = alert.textFields![0] as UITextField
        plantName2 = textField.text ?? "Name"
        appendItem()
    })
       showAlert(alert: alert)
}

private func appendItem() {
    items.append(Item(title: plantName2))
}

struct HomePage: View {
@State var plantName2: String = ""
@State private var items: [Item] = []
@State private var editMode = EditMode.inactive
private static var count = 0

var body: some View {
    NavigationView {
        List {
            Section(header: Text("My Plants")) {
                ForEach(items) { item in
                    NavigationLink(destination: PlantView(plantName3: item.title)) {
                        Text(item.title)
                    }
                }
                .onDelete(perform: onDelete)
                .onMove(perform: onMove)
                .onInsert(of: [String(kUTTypeURL)], perform: onInsert)
            }
        }
        .listStyle(InsetGroupedListStyle()) // or GroupedListStyle
        .navigationBarTitle("Plantify")
        .navigationBarTitleTextColor(CustomColor.pastelGreen)
        .navigationBarItems(leading: EditButton().accentColor(CustomColor.pastelGreen), trailing: addButton)
        .environment(\.editMode, $editMode)
    }
}

并且我希望将用户添加的条目保存在持久存储中。我查看了有关持久存储的文档,有点困惑。我的代码甚至可以吗?

谢谢!

【问题讨论】:

  • 持久存储非常模糊。你必须选择一个。 CoreData、JSON 文件、远程数据库等。您还混合了 SwiftUI 和 UIKit,但没有展示如何混合它们。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: swift swiftui


【解决方案1】:

基本上你可以将数据保存为UserDefaults中的String数组

func save() {
   UserDefaults.standard.set(items.map(\.title), forKey: "items")
} 

func load() {
   let savedItems = UserDefaults.standard.stringArray(forKey: "items") ?? []
   items = savedItems.map(Item.init)
}

并在.onAppear 中致电load

但是,如果有大量项目,请考虑 Documents 文件夹或 Core Data 中的文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2018-07-29
    相关资源
    最近更新 更多