在XCode Playgrounds

时间:2017-02-10 12:58:03

标签: ios xcode uitableview reuseidentifier

尝试在XCode Playgrounds中使用Table来理解它是如何工作的,因为有很多东西连接到UITableView,一些教程在场景下描述了这些关系和继承(比如{{1} } - > UIView - > UIScrollView - > UITableView)以及它如何管理继承,连接和委托。通常情况下,对于普通的导师,您将获得代码片段以及如何在XCode中建立委托连接以及正确的调用方法的说明。结果 - 您记住了这些步骤,但仍然不了解表的机制。下面是我尝试为XCode Playgrounds绘制一个简单表格的代码片段。问题 - 我无法以编程方式正确地注册表格单元格中的表格或其外部的标识符。错误的本质

  

原因:'无法使用标识符Cell将单元格出列 - 必须为标识符注册一个nib或类,或者在故事板中连接原型单元格'。

请帮助并指出错误和原因。

UITableViewCell

2 个答案:

答案 0 :(得分:1)

经过长时间使用各种教程构建表的不同解决方案后,我终于发现UITableViewControllerUIViewController之间在显示UITableView时有所不同。在我的问题的例子中,一些代码行是多余的。之所以发生这种情况是因为我试图在UIViewController内实现构建表的方法,但我使用UITableViewController代替了另外尝试设置dataSource和所有视图属性,但是因为我现在明白了 - UITableViewController已经为我做了所有这些事情(如果我错了,请在这里纠正我)。功能代码片段如下:

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()

    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

    } 
}

PlaygroundPage.current.liveView = TableViewController()

答案 1 :(得分:1)

在包含UITableView的UIViewController中,以编程方式将Custom UITableViewCell子类注册到UITableView的实例是通过以下方式实现的:
- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier

这是在设置表dataSource之前注册