OGeek|极客世界-中国程序员成长平台

标题: ios - TableView 外部数据源和委托(delegate)未加载 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:16
标题: ios - TableView 外部数据源和委托(delegate)未加载

我有一个以编程方式添加的表格 View ,我想将委托(delegate)和数据源连接到外部类。代码看起来正确,但是 tableview 被添加到 View 中,而没有从外部类中获取单元格布局。

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
}

}

谢谢



Best Answer-推荐答案


当使用不在 Storyboard 或类似内容中的 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")

关于ios - TableView 外部数据源和委托(delegate)未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42832395/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4