ios - TableView 单元格描述

标签 ios swift uitableview

我正在学习 iOS 在线类(class)。我正在使用 Swift 4.2。

我的问题是关于这个方法:

// This function is defining each cell and adding contenet to it.
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")

        cell.textLabel?.text = cellContent[indexPath.row]

        return cell

    }

上述方法在下面的代码中究竟是如何工作的?我知道上面的方法描述了 TableView 的每个单元格,但是 TableView 是否会为每一行调用它?

indexpath.row 到底是什么意思?我对这个感到困惑。

请帮帮我。谢谢。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var cellContent:Array<String> = ["Amir", "Akbar", "Anthony"]


    // This function is setting the total number of cells in the table view
    internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return cellContent.count

    }

    // This function is defining each cell and adding contenet to it.
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")

        cell.textLabel?.text = cellContent[indexPath.row]

        return cell

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


}

最佳答案

Apple's documentation在 IndexPath 上说:索引路径中的每个索引表示从树中的一个节点到另一个更深的节点的子数组的索引。

用简单的英语来说,它基本上意味着 IndexPath 是一种访问二维数组的方法,这就是 tableView 的 dataSource。 tableView 需要知道它有多少个部分,以及每个部分有多少行。

在您的情况下,只有一个部分,因此您无需担心 indexPath.section,因为该部分始终为 0。只有一个数组(您的 cellContent 数组)在 tableView 的多维数据源中,因此您可以使用 indexPath.row 访问元素。如果您有多个 cellsContent 数组,则必须先使用 indexPath.section 访问正确的数组,然后才能使用 indexPath.row

您省略了 UITableViewDatasourcenumberOfSections 方法,它默认返回 1

关于ios - TableView 单元格描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55318144/

相关文章:

ios - 无法在 AudioFileStreamOpen 的 AudioFileStream_PacketsProc 回调中使用 AudioConverterFillComplexBuffer 将 mp3 转换为 PCM

ios - 根据行高在 UITableViewCell 中移动 UIImage

ios - 在 HTTP 方法中使用 POST 请求保存 UI?

iOS 应用程序 Ping 用户喜欢查找我的 iphone "Play a Sound"

ios - Firebase - .value 上的索引未给出排序结果

ios - 结构文件可以有任何名称(在这种情况下)吗?

iOS构建从jenkins到曲棍球应用程序上传失败

swift - 尽管使用 SwiftUI 成功解码 json 数据,但没有图像

ios - UITableView 动态大小

ios - 如果行数据与前一行匹配,则对 UITableView 中的行进行编号并复制行号