ios - 在 XCode Playgrounds 中注册单元重用标识符

标签 ios xcode uitableview reuseidentifier

尝试在 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/

相关文章:

ios - 在 iPad 上使用 Swift UI 禁用 Split View

ios - 无法从iOS 10中的App组共享容器中获取扩展应用程序中的图像

swift - 根据优先级在 Tableview 中自动排列行 - Swift 3/4

ios - 为什么 UITableView 在同时滚动和更新时会丢失部分标题?

ios - 仅在调试变体上启用 UIFileSharingEnabled

ios - 在 uitableview 中显示 vcard 数据

iphone - 使用 GCD 完成 block

ios - "nw_endpoint_flow_copy_multipath_subflow_counts Called on non-Multipath connection"导致搜索栏出现问题

objective-c - 我们如何将 double 或 float 重新解释为 NSUInteger 来创建哈希?

ios - 在 iOS 中如何使用 bool 结果检查字符串是否符合正则表达式