首页 > 解决方案 > 表格视图单元格说明

问题描述

我在网上学习一门课程来学习 iOS。我正在使用 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

    }

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

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.
    }


}

标签: iosswiftuitableview

解决方案


Apple关于 IndexPath 的文档说:索引路径中的每个索引都表示从树中的一个节点到另一个更深节点的子数组的索引。

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

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

您省略了默认返回的numberOfSections方法。UITableViewDatasource1


推荐阅读