从一个普通的类加载tableview

时间:2019-05-29 06:21:18

标签: ios swift tableview

我有这个特定的类,可以处理从任何viewcontroller加载tableview的操作。给出为..

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)
    }
  }

}

此类将处理来自任何viewcontroller的数据的表视图加载。

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

1 个答案:

答案 0 :(得分:0)

您必须执行类似yourViewController Tableview.delegate = TableViewConfig

的操作
相关问题