首页 > 解决方案 > 在 UITableview 中保存数据

问题描述

我有一个应用程序,用户可以通过填充表格视图将书籍添加到收藏夹列表中。这本书的详细信息显示在一个视图中,通过点击“收藏夹”,执行一个 segue,将该书的信息输入到 tableview 单元格中。

目前,一次只能在表格中出现一本书添加新书将删除初始条目(因此实际上只使用了 tableview 的第一个单元格)

有没有办法在表格视图中保存每个条目,所以实际上创建了一个收藏夹列表

保存按钮

 @IBAction func saveButton(_ sender: Any) {

        let bookFormat = formatLabel.text

        if (bookFormat!.isEmpty)
        {
            displayMyAlertMessage(userMessage: "Please Select a Book Format")
            return
        }
        else{

        self.performSegue(withIdentifier: "LibViewSegue", sender: self)
        }


    }

表视图

extension LibrarybookViewController: UITableViewDataSource, UITableViewDelegate{

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 115
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(#function, dataSource.count)

        return dataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->  UITableViewCell {
        print(#function, "indexPath", indexPath)
        guard let bookCell = tableView.dequeueReusableCell(withIdentifier: "libCell", for: indexPath) as? LibrarybookTableViewCell else {
            return UITableViewCell()
        }
        let libbook = dataSource[indexPath.row]




        bookCell.cellTitleLabel.text = libbook.title
        bookCell.cellReleaseLabel.text = libbook.release
        bookCell.cellFormatLabel.text = bookFormat




        return bookCell
    }

我一直在阅读有关默认值和 CoreData 的信息,但我不确定这是否应该在 segue 按钮操作或 tableview 函数中实现?

标签: swiftuitableviewcore-datadatapersistance

解决方案


我看到你有一个包含书籍列表的 dataSource 数组。在最简单的情况下,您可以将数据附加到您的数据源,然后重新加载您的 UITableView。但是,如果您想要持久存储,您可以查看本地数据库解决方案,如 SQLite、CoreData 或 Realm。那么这只是存储-> 获取数据-> 在 UITableView 上显示的问题。

一般的想法是添加按钮点击(或您想要附加操作的任何事件侦听器),将其保存到持久存储,重新加载您的 tableView,因为数据源来自持久存储,它会自动更新。假设您从持久存储中加载数据。

另外,不要将您的数组存储在 UserDefaults 中,它是用于用户会话等的小数据。

编辑:正如@Leo Dabus指出的那样,您确实可以插入行而不使用重新加载tableView

let index = IndexPath(row: items.count - 1, section: 0) // replace row with position you want to insert to.
tableView.beginUpdates()
tableView.insertRows(at: [index], with: .automatic)
tableView.endUpdates()

推荐阅读