【问题标题】:Saving Data in UITableview在 UITableview 中保存数据
【发布时间】:2020-07-31 16:04:01
【问题描述】:

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

目前一次只能在表格中出现一本书,添加新书将删除初始条目(因此实际上只使用了 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 函数中实现?

【问题讨论】:

    标签: swift uitableview core-data datapersistance


    【解决方案1】:

    我看到您有一个包含书籍列表的 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()
    

    【讨论】:

    • 为什么要重新加载? UITableView 有一种方法可以插入新行而无需全部重新加载。
    • @LeoDabus 你是对的,应该将它包含在原始答案中,感谢您的提醒!
    • 单行插入无需调用开始更新
    • 顺便说一句,如果您需要进行多次插入、删除、移动和/或重新加载,您应该使用 performBatchUpdates developer.apple.com/documentation/uikit/uitableview/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多