为什么numberOfRowsInSection只有一个部分被多次调用?

// Variable and ViewDidLoad var auxRow = 0 var auxSection = 0 override func viewDidLoad() { super.viewDidLoad() } 

//节数,只有一个部分

  override func numberOfSectionsInTableView(tableView: UITableView) -> Int { auxSection += 1 print("times section: ", auxSection) return 1 } 

//行数

 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { auxRow += 1 print("times row: ", auxRow) return 2 } 

// TableViewconfiguration单元格

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let textCellIdentifier = "cellText" let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) let variable : String = indexPath.row.description cell.textLabel?.text = variable return cell } 

输出:

  times section: 1 times row: 1 times section: 2 times row: 2 times section: 3 times row: 3 times section: 4 times row: 4 

numberOfRowsInSection方法被调用4次。 为什么会这样呢?

Apple不保证UIKit可能会多久调用一次您的委托方法。 他们拥有这个框架。 我们可以期望他们caching这个值,但没有任何要求他们这样做。

你可以在你的numberOfRowsInSection方法中设置一个断点来查看它在内部的使用情况。 没有理由不应该多次调用它,因为任何时候tableview在内部都需要知道它有多less行。 它被称为4次,因为苹果的tableview代码需要知道,在4个不同的时间,在一个部分有多less行。