尝试在 XCode Playgrounds 中使用 Table 来了解它是如何工作的,因为有很多东西连接到 UITableView
并且一些教程在场景下描述了这些关系和继承(例如 UIView
-> UIScrollView
-> UITableView
-> UITableViewCell
)以及它如何管理继承、连接和委托(delegate)。通常,普通导师会为您提供代码片段以及如何在 XCode 中建立委托(delegate)连接以及调用的正确方法的说明。结果——你记住了步骤,但仍然不理解表格的机制。下面是我尝试采用 XCode Playgrounds 绘制一个简单表格的代码片段。问题 - 我无法以编程方式正确注册表单元格的重用标识符,无论是从类还是外部。错误的性质
reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'.
请帮忙指出问题所在以及原因。
class TableViewController: UITableViewController {
let tableData = ["Matthew", "Mark", "Luke", "John"]
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
cell.textLabel?.text = tableData[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
//Did this part as comments to try to do this outside the class
// self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
// self.tableView = UITableView(frame:self.view.frame)
// self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.view.addSubview(self.tableView)
}
}
let frame = CGRect(x: 0, y: 0, width: 320, height: 480)
let tableView = UITableView(frame: frame, style: .plain)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
PlaygroundPage.current.liveView = TableViewController()
最佳答案
在包含 UITableView 的 UIViewController 中,以编程方式将自定义 UITableViewCell 子类注册到 UITableView 的实例是通过以下方式实现的:
- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier
这是注册类应该在设置表的数据源
之前完成。
关于ios - 在 XCode Playgrounds 中注册单元重用标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42159987/