我正在尝试用代码中的示例数据填充基本 TableView 。这是我的 View Controller :
import UIKit
class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var postTableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postcell", for: indexPath)
cell.textLabel?.text = "title"
cell.detailTextLabel?.text = "detail"
return cell
}
}
我确定名称 “postcell”
是正确的,并且我已将 tableView 作为数据源和委托(delegate)连接到 ViewController。
当我在 iOS 模拟器中运行代码时,没有显示任何单元格。这是我看到的:
堆栈 View 属性
我不想使用UITableViewController
如何让表格单元格出现?
最佳答案
如果“postcell”不是 Storyboard中的原型(prototype)单元格,则需要在 viewDidLoad 中注册它:
postTableView.register(UITableViewCell.self, forCellReuseIdentifier: "postcell")
如果它是一个 XIB TableView 单元格,您将按如下方式注册它:
postTableView.register(UINib(nibName: "NibName", bundle: nil), forCellReuseIdentifier: "postcell")
如果您要从 Storyboard 中执行此操作,请将原型(prototype)单元格(或表格 View 单元格)拖到您的表格 View 上,并在重用标识符中将其称为“postcell”,如下所示:
确保您还在 viewDidLoad 中完成了以下操作:
postTableView.delegate = self
postTableView.dataSource = self
当然,你还需要:
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
关于ios - 为什么我的 tableView 没有被填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619686/