Nin*_*per 5 count uitableview testcase swift
我正在编写一个UIViewController
具有UITableView 的测试用例.我想问一下如何在UITableView中获取行数
func testloadingDataIntoUiTableView()
{
var countRow:Int = viewController.formListTableView.numberOfRowsInSection
XCTAssert(countRow == 4)
}
Run Code Online (Sandbox Code Playgroud)
Luc*_*tti 10
请记住,数据模型会生成UI.但是你不应该查询UI来检索你的数据模型(除非我们讨论的是用户输入).
让我们看看这个例子
class Controller:UITableViewController {
let animals = ["Tiger", "Leopard", "Snow Leopard", "Lion", "Mountain Lion"]
let places = ["Maveriks", "Yosemite", "El Capitan"];
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return animals.count
case 1: return places.count
default: fatalError()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier("MyCellID") else { fatalError("Who took the MyCellID cell???") }
switch indexPath.section {
case 0: cell.textLabel?.text = animals[indexPath.row]
case 1: cell.textLabel?.text = places[indexPath.row]
default: fatalError()
}
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,要获取表中的总行数,我们应该查询模型(animals
和places
属性),所以
let controller: Controller = ...
let rows = controller.animals.count + controller.places.count
Run Code Online (Sandbox Code Playgroud)
或者甚至更好,我们可以使animals
和places
属性私有,并添加这样的计算属性
class Controller:UITableViewController {
private let animals = ["Tiger", "Leopard", "Snow Leopard", "Lion", "Mountain Lion"]
private let places = ["Maveriks", "Yosemite", "El Capitan"];
var totalNumberOfRows: Int { return animals.count + places.count }
...
Run Code Online (Sandbox Code Playgroud)
现在你可以使用它了
let controller: Controller = ...
let rows = controller.totalNumberOfRows
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7026 次 |
最近记录: |