Show TableView in Swift Playgrounds for iPad

坚强是说给别人听的谎言 提交于 2019-12-22 10:45:49

问题


Everything works fine except the last line where I try to show the tableView in live view does not work: PlaygroundPage.current.liveView = controller

I can't figure out what I'm getting wrong?

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

回答1:


I think you forgot to register the table view cell class in viewDidLoad()

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



回答2:


In func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath), add one line to the top of the function:

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

Like this:

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

}


来源:https://stackoverflow.com/questions/39682759/show-tableview-in-swift-playgrounds-for-ipad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!