如何以编程方式将单元格添加到 UITableview 并使用来自 myArray[cellNumber]
的数据填充单元格。
数组中的数据是字符串类型。 tableview 只是一个连接了 outlet 的 UITableView。
我找到的所有示例要么是 +30 行,要么不起作用... 我正在使用 swift 4 和 UIKit。
最佳答案
- 在 Xcode 中,使用“File > New > File > Cocoa Touch Class”。
- 使用
UITableViewController
作为基类 你会发现一个很大的模板,只需执行:
numberOfSections(in tableView: UITableView) -> Int
,让它返回 1。你现在只需要一个部分。tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
,让它返回数组的大小覆盖 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
。取消注释,实现它。注意:要实现 tableView(_:cellForRowAt:),您必须在 Storyboard中注册一个单元格,并在此函数中使用它的名称。或者使用 register(_:forCellReuseIdentifier:) 以编程方式注册单元格.
这里有一份更全面的指南iOS Getting Started Guide UITableView
实现示例:
override func numberOfSections(in tableView: UITableView) -> Int {
return 1 // Only one section
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// "cell" is registered in the Storyboard
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// The registered cell, has a view with tag 1 that is UILabel as an example
// IndexPath is a data structure that has "section" and "row"
// It located the cell in your tableview/collectionview
(cell.viewWithTag(1) as? UILabel)?.text = myArray[indexPath.row]
return cell
}
关于Swift:将包含自定义标签的单元格添加到 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48787275/