试图在XCode Playgrounds中使用表格来了解它是如何工作的,因为有很多东西连接到UITableView
,并且一些教程描述了这些关系和场景下的继承(如UIView
- >UIScrollView
- >UITableView
- >UITableViewCell
)以及它如何管理继承,连接和委派。通常,对于普通的导师,您将获得代码片段以及如何在XCode中建立委托连接以及调用正确方法的说明。结果 - 你记住了这些步骤,但仍然不理解表的机制。以下是我尝试采用XCode Playgrounds绘制简单表格的代码片段。这个问题 - 我无法正确注册程序化的表格单元格的重用标识符,从类或其外部。错误的性质在XCode Playgrounds中注册单元重用标识符
原因:'无法使标识符单元出队 - 必须为标识符注册一个nib或类或连接故事板中的原型单元格。
请帮忙指出什么是错的,为什么。
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()
感谢您的回复!这也是如此。但是为什么当我忽略设置表的'dataSource'时代码正常工作。 UITableViewController默认使用self作为表'dataSource'? –
是的,当你继承一个'UITableViewController'时,它执行(免费)设置数据和(抽头)委托处理程序到'self','UITableViewController'的实例。 – ystack
对于Swift 3,其语法是:'tableView.register(MyCustomTableViewCell.classForCoder(),forCellReuseIdentifier:“Cell”)''。这是写在'loadView()'或'viewDidLoad()'中的'UITableViewController'里面。 –