ios - 表格视图单元格说明
问题描述
我在网上学习一门课程来学习 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.
}
}
解决方案
Apple关于 IndexPath 的文档说:索引路径中的每个索引都表示从树中的一个节点到另一个更深节点的子数组的索引。
用简单的英语来说,它基本上意味着IndexPath
s 是一种访问二维数组的方法,这就是dataSource
tableView 的含义。tableView 需要知道它有多少个部分,以及每个部分有多少行。
在您的情况下,只有一个部分,因此您无需担心,indexPath.section
因为该部分始终为 0。 的多维数据源中只有一个数组(您的cellContent
数组),tableView
因此您可以使用indexPath.row
. 如果您有多个 cellsContent 数组,则必须indexPath.section
先访问正确的数组,然后才能使用indexPath.row
您省略了默认返回的numberOfSections
方法。UITableViewDatasource
1
推荐阅读
- python - 如何在列表列表中添加换行符?
- memory - e-LMC扩展小人电脑泡泡嵌入式程序连续输入
- python - 使用枕头和 discord.py 裁剪图像问题
- python - 运行此 Python 代码时遇到“MemoryError”
- ios - Fastlane iOS 不工作。在获取证书和配置文件时正在显示正在克隆远程 git repo...
- flutter - Flutter:查询 AWS AppSync
- angular - 如何以角度导入 npm 包?
- c# - 在 Windows 切换线程之前强制完成对 ac# 方法的异步调用
- php - 此集合实例上不存在属性 [customInput]
- java - 为什么这个代码段不会产生结果?