ios - 从公共(public)类加载表格 View

标签 ios swift tableview

我有这个特定的类,它可以处理从任何 View Controller 加载表格 View 。它被给出为..

class TableViewConfig<ItemsType, CellType:UITableViewCell>: NSObject, UITableViewDataSource, UITableViewDelegate {

  var emptyDataSet: Bool {
    didSet {
      if emptyDataSet {
        tableView.tableFooterView = UIView()
      }
    }
  }

  var items: [ItemsType] {
    didSet {
      tableView.dataSource = self
      tableView.delegate = self
      tableView.reloadData()
    }
  }

  // MARK: - Private Properties
  typealias CellClosure = (_ item: ItemsType, _ cell: CellType) -> Void

  // Tableview Config
  private var tableView: UITableView
  private var cellIdentifier: String
  private var configureCellClosure: CellClosure

  // Delegate
  private var indexPathClosure: ((IndexPath?) -> Void)?

  // MARK: - Public Methods
  public func selectedRow(_ callBack: @escaping (IndexPath?) -> Void) {
    indexPathClosure = callBack
  }

  // MARK: - Inialization
  init(_ tableView: UITableView,
       items: [ItemsType],
       cellIdentifier identifier: String,
       configClosure config:@escaping CellClosure) {

    self.tableView = tableView
    self.cellIdentifier = identifier
    self.items = items
    self.configureCellClosure = config
    self.emptyDataSet = false
  }

  // MARK: UITableViewDataSource
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as! CellType
    cell.tag = indexPath.row
    configureCellClosure(items[indexPath.row], cell)
    return cell
  }

  private func item(at indexpath: IndexPath) -> ItemsType {
    return items[indexpath.row]
  }

  // MARK: UITableViewDelegate
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let callback = indexPathClosure {
      callback (indexPath)
    }
  }

}

此类将处理带有来自任何 View Controller 的数据的 TableView 的加载。

现在我的问题是我想使用这个类并在我的 View Controller 中显示一个表格 View 。我怎样才能做到这一点..?希望有人能帮忙...

最佳答案

你必须做类似你的 ViewController Tableview.delegate = TableView Config 的事情

关于ios - 从公共(public)类加载表格 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56354255/

相关文章:

ios - 如何区分用户是用手指还是苹果铅笔点击屏幕?

ios - SKPhysicsBody 的 .dynamic 属性

ios - 当不再显示 UIViewController 时如何继续 CAKeyframeAnimation?

json - 如何从 JSON 二维结构(嵌套字典)获取值?

ios - 以编程方式启用按钮需要几秒钟

swift - Swift 中的基础数学

swift - 从 Firebase 获取信息 : Swift

objective-c - NSWindow 内存选项

ios - 我应该在我的 TableView 中使用 4 xib 还是使用 4 个不同的 TableView

Swift:如何从 UITableViewCell、Action sheet 进行 segue