在 Swift 游乐场中显示 TableView iPad

Show TableView in Swift Playgrounds for iPad

除最后一行我尝试在实时取景中显示 tableView 外,一切正常:PlaygroundPage.current.liveView = controller

我不知道我哪里错了?

import UIKit
import PlaygroundSupport
import Foundation

class TableViewController: UITableViewController {
    let tableData = ["Matthew", "Mark", "Luke", "John"]

override func viewDidLoad() {
    super.viewDidLoad()
    print("Hello Matt")
}

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 {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
    cell.textLabel?.text = tableData[indexPath.row]
    return cell
}
}

let controller = TableViewController()
PlaygroundPage.current.liveView = controller

我想你忘了在 viewDidLoad()

中注册 table 视图单元格 class
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)中,在函数的顶部添加一行:

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

像这样:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
    cell.textLabel?.text = tableData[indexPath.row]
    return cell

}