TableView外部dataSource和Delegate未加载

时间:2017-03-16 11:09:41

标签: ios swift uitableview

我有一个以编程方式添加的tableview,我希望将委托和dataSource连接到外部类。代码看起来正确但是tableview被添加到视图中而没有从外部类获取单元格布局。

let tableView: UITableView = {
    let dataService = ActivityDataService()
    let tb = UITableView()
    tb.tableHeaderView = nil
    tb.tableFooterView = nil
    tb.rowHeight = 50
    tb.estimatedRowHeight = 50
    tb.dataSource = dataService
    tb.delegate = dataService
    tb.register(ProfileActivitySubCell.self, forCellReuseIdentifier: "tableCell")
    return tb
}()

以下是活动服务类:

class ActivityDataService: NSObject, UITableViewDelegate, UITableViewDataSource {

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! ProfileActivitySubCell
    return cell
}

func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
    return 0
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 50
}

}

由于

3 个答案:

答案 0 :(得分:0)

使用不在故事板或类似内容中的UITableView时,您需要使用标识符注册单元格。

取决于你的UITableViewCell(如果它是一个子类和/或你是否正在使用nib)

您可以使用以下方法之一:

open func register(_ nib: UINib?, forCellReuseIdentifier identifier: String)

open func register(_ cellClass: Swift.AnyClass?, forCellReuseIdentifier identifier: String)

这是UITableView

的方法

在你的情况下可能是这样的:

tb.register(ProfileActivitySubCell.classForCoder(), forCellReuseIdentifier: "tableCell")

答案 1 :(得分:0)

1)将表视图数据源方法重构为单独的类

  class IceCreamListDataSource: NSObject, UITableViewDataSource
    {


      // MARK: - Table view data source

      func numberOfSectionsInTableView(tableView: UITableView) -> Int
      {
        return 1
      }

      func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
      {
        return 5
      }

      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
      {

        let cell = tableView.dequeueReusableCellWithIdentifier("IceCreamListCell", forIndexPath: indexPath)

        return cell
      }
    }

2)在您的控制器类中执行此操作 -

class IceCreamListViewController: UITableViewController
{
  let dataSource = IceCreamListDataSource()

  // MARK: - View lifecycle

  override func viewDidLoad()
  {
    super.viewDidLoad()
    tableView.dataSource = dataSource
  }
}

答案 2 :(得分:0)

我设法解决了这个问题。由于tableView在集合视图中,我不得不使用故事板对象插座。最后,在集合视图单元格中,我必须将委托和dataSource设置为新创建的对象。

cell.tableView.dataSource = dataService
cell.tableView.delegate = dataService
相关问题