菜鸟教程小白 发表于 2022-12-11 19:16:21

ios - TableView 外部数据源和委托(delegate)未加载


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

<pre><code>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: &#34;tableCell&#34;)
    return tb
}()
</code></pre>

<p>这里是事件服务类:</p>

<pre><code>class ActivityDataService: NSObject, UITableViewDelegate, UITableViewDataSource {

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

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

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

}
</code></pre>

<p>谢谢</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>当使用不在 Storyboard 或类似内容中的 <code>UITableView</code> 时,您需要使用标识符注册单元格。</p>

<p>取决于您的 <code>UITableViewCell</code>(如果它是子类和/或您是否使用 nib)</p>

<p>您可以使用以下方法之一:</p>

<pre><code>open func register(_ nib: UINib?, forCellReuseIdentifier identifier: String)

open func register(_ cellClass: Swift.AnyClass?, forCellReuseIdentifier identifier: String)
</code></pre>

<p><code>UITableView</code></p>的方法是什么

<p>在你的情况下可能是这样的:</p>

<p><code>tb.register(ProfileActivitySubCell.classForCoder(), forCellReuseIdentifier: "tableCell")</code></p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - TableView 外部数据源和委托(delegate)未加载,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42832395/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42832395/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - TableView 外部数据源和委托(delegate)未加载