在Swift Playgrounds for iPad中显示TableView

问题描述 投票:3回答:2

一切正常,除了最后一行,我试图在实时视图中显示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
ios swift uitableview swift-playground
2个回答
6
投票

我想你忘了在viewDidLoad()注册表视图单元类

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

1
投票

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

}
© www.soinside.com 2019 - 2024. All rights reserved.