我正在学习 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
您省略了 UITableViewDatasource
的 numberOfSections
方法,它默认返回 1
。
关于ios - TableView 单元格描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55318144/