[英]Table View Cell Description
我正在网上学习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.
}
}
苹果公司在IndexPath上的文档说:索引路径中的每个索引代表从树中一个节点到另一个更深节点的子级数组的索引。
用通俗的英语来说,它基本上意味着IndexPath
是访问二维数组的一种方法,而tableView的dataSource
就是这种二维数组。 tableView需要知道它有多少节,以及每个节中有多少行。
在你的情况下,只有一个部分,所以你不必担心indexPath.section
因为部分始终为0,只有一个数组(您cellContent
阵列)在tableView
的多维数据源,所以你可以使用访问元素indexPath.row
。 如果您有不止一个cellsContent Array,则必须先使用indexPath.section
来访问正确的一个,然后才能使用indexPath.row
您已经省略了UITableViewDatasource
的numberOfSections
方法,该方法默认情况下返回1
。
除了汤姆·皮尔森(Tom Pearson)在IndexPath上的答案外,
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
是的,为tableView中的每个可见单元格调用此方法。
如果在cellForRowAt方法中使用下面的方法,则将在不实例化更多单元对象的情况下重用单元。
let cell = tableView.dequeueReusableCell(withIdentifier: action,
for: indexPath as IndexPath)
一旦该单元格失去可见性(可以滚动),该单元格对象将重新用于新的可见行,并且不会为每个单元格新创建该对象。 这就是这种方法的强大之处。
通常,代码将是这样的。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "someIdentifier",
for: indexPath as IndexPath) as? SomeCell else {
fatalError("Cell is not of type SomeCell")
}
cell.title.font = somefont
cell.title?.textColor = somecolor
cell.backgroundColor = UIColor.clear
return cell
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.