gpt4 book ai didi

ios - tableView.cellForRow(在 :) and tableView. dataSource?tableView(tableView:cellForRowAt :) 之间的区别

转载 作者:可可西里 更新时间:2023-11-01 00:54:20 24 4
gpt4 key购买 nike

我正在对 tableView 是否呈现单元格进行单元测试。

我发现 tableView.cellForRow(at:) 返回 nil,而 tableView.dataSource?tableView(tableView:cellForRowAt:) 返回正确的单元格。

这是我的单元测试代码。

it("renders one option text") {
let indexPath = IndexPath(row: 0, section: 0)

let cell = sut.tableView.dataSource?.tableView(sut.tableView, cellForRowAt: indexPath)

let cell2 = sut.tableView.cellForRow(at: indexPath)

expect(cell?.textLabel?.text).toEventually(equal("A1")) // test suceeded
expect(cell2?.textLabel?.text).toEventually(equal("A1")) // test failed
}

所以我很好奇这两种方法的区别。

Apple 的文档说如果单元格不可见,tableView.cellForRow(at:) 返回 nil,所以我理解 tableView.cellForRow(at:)单元测试时返回 nil,但我不确定 调用这两种方法的时间顺序 以及 tableView.cellForRow(at:) 获得正确值(单元格)的时间 .

最佳答案

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

此方法用于根据 tableView 的要求生成或出列单元格。这不是 UITableView 成员方法。相反,它是一个协议(protocol)方法,另一个对象(将成为数据源)将实现并返回值。因此,无论我们是在进行单元测试还是在调试应用程序,它总是会返回一个单元格。

tableView.cellForRow(at:) 

此方法不是生成器方法。它是 UITableView 的成员方法,作为 eg 的实用方法。为了获取选定的行,我们使用 tableView.selectedRow。所以它应该返回任何 indexPath 的单元格。

正如我们所知,UITableView 不会创建与绘制的行相等的单元格。假设你想绘制 100 行,然后 UITableView 只创建除了可见单元格之外的几个额外单元格。因此,如果您传递任何不在可见行中的 indexPath,那么实际上该单元格不存在。因为 tableview 正在等待您滚动并重复使用未使用的单元格。因此,无论您是在进行单元测试还是在应用程序上工作,对于不可见的单元格,它始终会显示为 nil。

关于ios - tableView.cellForRow(在 :) and tableView. dataSource?tableView(tableView:cellForRowAt :) 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53735018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com