2016-03-25 155 views
1
// Variable and ViewDidLoad 

var auxRow = 0 
var auxSection = 0 

override func viewDidLoad() { 
    super.viewDidLoad() 
} 

//数量的部分中,只有一个部分为什么numberOfRowsInSection仅针对一个部分被多次调用?

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 
} 

// TableView中配置细胞

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次。为什么会发生?

+0

我不明白为什么在方法numberOfRowsInSection中输入4次。我只有一个部分 – PedroMeira

+1

@Lamar:OP询问为什么numberOfRowsInSection方法执行4次,因为他只有1个部分(不是4个部分,所以理论上它应该只执行一次) –

+0

numberOfRowsInSection方法执行4次,因为?是什么原因? – PedroMeira

回答

5

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

2

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

+0

它被称为4倍numberOfRowsInSection和numberOfSectionsInTableView - > 倍部分:1 次行:1 倍部分:2 倍行:2 倍部分:3 次行:3 倍截面:4 倍行: 4 – PedroMeira

+1

@PedroMeira对不起,但我不明白这应该是什么意思 –

+1

这两种方法可以调用任意次数,这取决于tableview在内部如何使用它们。它不是100%绑定到您的tableview所具有的行数或节数。 –

相关问题