【问题标题】:Why is the numberOfRowsInSection being called multiple times for only one section?为什么只有一个部分多次调用 numberOfRowsInSection ?
【发布时间】:2016-07-13 11:58:22
【问题描述】:
// 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
}

// 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 次。为什么会这样?

【问题讨论】:

  • 我不明白为什么在方法 numberOfRowsInSection 中输入 4 次。我只有一节
  • @Lamar:OP 在问为什么 numberOfRowsInSection 方法执行 4 次,因为他只有 1 个部分(不是 4 个部分,所以理论上该方法应该只执行一次)
  • numberOfRowsInSection 方法执行 4 次,因为?是什么原因?
  • 这有关系吗?它给你带来了问题吗?只有了解 Apple 源代码的人才能真正告诉您……
  • numberOfRowsInSection 方法将返回您的tableview 的行数。因为您的数据结构中有4 个对象。它将返回 4 行

标签: ios arrays swift uitableview tableview


【解决方案1】:

Apple 不保证 UIKit 调用您的委托方法之一的频率。他们拥有框架。我们可以期望他们缓存该值,但没有什么要求他们这样做。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 被称为 4 次 numberOfRowsInSection 和 numberOfSectionsInTableView -> 次段:1 次行:1 次段:2 次行:2 次段:3 次行:3 次段:4 次行:4
    • @PedroMeira 很抱歉,但我不明白这应该是什么意思
    • 这两种方法都可以调用任意次数,具体取决于 tableview 在内部如何使用它们。它不是 100% 与您的 tableview 拥有的行数或部分数相关。
    • 我只有一个section,方法numberOfRowsInSection应该只调用一次,为什么要调用4次?我更改了问题代码,方法 numberOfSectionsInTableView 被调用了 4 次。是什么原因?我不明白为什么会这样,想看看是不是我做错了什么
    • “我只有一​​个部分,方法 numberOfRowsInSection 应该只调用一次”是不正确的。你的基本假设是错误的。正确的是“我只有一​​个部分,方法 numberOfRowsInSection 应该被调用多次,因为 Apple 的 tableview 代码想要调用它,在我的例子中是 4。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多