在 iPad 的 Swift Playgrounds 中显示 TableView

4

除了最后一行代码 PlaygroundPage.current.liveView = controller 无法在实时视图中显示tableView外,其他都正常运作。

我无法弄清楚我的错误在哪里?

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

什么不起作用?有错误吗?会发生什么? - Jack Lawrence
@JackLawrence,akosma解决了这个问题,非常感谢你的关注和检查。 - SRMR
1
https://gist.github.com/watert/13c38d269ea15aa8360f - StackUnderflow
2个回答

9

我认为你忘记在 viewDidLoad() 中注册表格视图单元格类了。

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}

2
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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接