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

标签 ios swift unit-testing uitableview

我正在 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 的成员方法,作为实用方法,例如。为了获取选定的行,我们使用 tableView.selectedRow。所以它应该返回任何索引路径的单元格。

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

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

相关文章:

ios - NSManagedObject 类关系中的 NSPredicate 键

iOS 如何修复自定义 UITableView 单元格中的 UIButton 高度

xcode - NSTextView 自动完成和标签转换

ios - 自定义类 View 和选择器引用

android - TestScope 在协程测试中的高级使用示例

ios - 在 UIViewController 中覆盖 View 事件时省略 [super] 调用。影响?

iphone - 使用 NSRegularExpression 匹配 HTML

javascript - 如何在 JUnit 测试中测试 wicket ajaxBehavior 上附加的 javascript?

java - 在 Android 中运行单元测试时, Intent 解析为不同的进程

iPhone: float 后应该有多少位数字