【问题标题】:how to reload data in tableview inside tableview controller cell correctly in swift 4?如何在 swift 4 中正确重新加载 tableview 控制器单元格内的 tableview 中的数据?
【发布时间】:2018-06-01 16:16:49
【问题描述】:

我在其中一个 tableview 控制器(名为 A)单元格中有一个表视图(名为 B),我在 tableView A 单元格(名为 add)中有一个按钮,在该单元格中我有 tableview B 和 tableview B 有一个按钮(名为删除)和每个单元格的文本字段,所以我希望当用户按下添加按钮表视图 B 时重新加载并有一个新行,当用户按下删除按钮表视图 B 时重新加载并删除该行以便更好地理解我有一个视频,你可以在这里查看链接 https://ufile.io/5x6y1

在这个视频中,你可以看到会发生什么以及我想做什么

这是主表视图类中删除和添加按钮的代码(记住表视图A单元格中的添加按钮(主表视图单元格和删除按钮在表视图B单元格中) (在主表视图(表视图 A)单元格内的表视图 B 中的每个单元格中)

    var certificates = [String]()
    if self.pf.Licences.count != 0 {
               for i in 0...self.pf.Licences.count - 1 {
                    print(self.pf.Licences[i].title!)
                            self.certificates.append(self.pf.Licences[i].title!)
                        }
                    }
                    self.tableView.reloadData()
                }

 @IBAction func deleteCer(_ sender: UIButton) {

    print("delete")
    let buttonRow = sender.tag
    certificates.remove(at: buttonRow)
    DispatchQueue.main.async {
        self.tableView.reloadRows(at: [IndexPath.init(row: 0, section: 6)], with: .right)
    }
}

@IBAction func addingCertificate(_ sender: UIButton) {

    print("add")
    if certificates.count != 0 {
        if certificates[certificates.count - 1] != "" {
            certificates.append("")
            DispatchQueue.main.async {
                self.tableView.reloadRows(at: [IndexPath.init(row: 0, section: 6)], with: .bottom)
                }
            }
        }
        else {
           print(certificates)
           certificates.append("")
            print(certificates)

            DispatchQueue.main.async {
                self.tableView.reloadRows(at: [IndexPath.init(row: 0, section: 6)], with: .bottom)

        }
    }
}

【问题讨论】:

  • 你在哪里for i in 0...self.pf.Licences.count - 1你可以简化为for license in self.pf.Licences
  • 但是当我在 self.pf.Licences 中使用 license 时,我应该在 self.certificates.append(self.pf.Licences[i].title!) 中使用什么而不是 i
  • 除了将循环计数器用作从数组中检索数据的索引之外,您并没有对循环计数器做任何特别的事情。您没有任何基于索引的条件,这就是为什么您可以摆脱它并使用建议,因为它只会为您提供 Licenses 数组中的每个许可证。
  • 我使用了一个数组,因为许可证将从 Json 获取,我想附加一些数据,所以我有名为证书的主数组,当用户访问此页面时,证书将等于许可证数组,然后是用户可以删除或附加项目
  • 这与您只是访问每个许可证的标题无关。

标签: ios uitableview cell swift4


【解决方案1】:

为了使您的添加和删除工作有效,您需要在“插入、删除和移动行和节”部分下的https://developer.apple.com/documentation/uikit/uitableview 的 UITableView 上查看这些应该如何完成。

您基本上需要使用insertRows(at:with:)deleteRows(at:with:),同时确保您的数据源已更新。

如果你的 UITableView B 有某种控制器,你可能应该向它发送插入和删除消息,而不是父 UITableView A。

换一种说法,如果你使用certificates[certificates.count - 1],你可以只使用certificates.last

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 2014-12-16
    相关资源
    最近更新 更多