【发布时间】: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,但没有展示如何混合它们。
-
请提供足够的代码,以便其他人更好地理解或重现问题。