【发布时间】:2018-05-14 21:48:46
【问题描述】:
我正在尝试在 Swift 操场上添加 UITableView,但由于某种原因它没有加载。这是我的代码:
class MyViewController : UIViewController,UITableViewDelegate,UITableViewDataSource {
let content = ["One", "Two"]
var tableView = UITableView()
override func loadView() {
let view = UIView()
view.backgroundColor = .red
self.view = view
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blue
self.tableView = UITableView(frame: self.view.bounds, style: .plain)
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.content.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if cell.detailTextLabel == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "cell")
}
cell.textLabel?.text = self.content[indexPath.row]
return cell
}
}
PlaygroundPage.current.liveView = MyViewController()
你们有谁知道为什么 tableview 没有加载到视图中?
【问题讨论】:
-
可能是因为表格视图是空的?
-
确认
viewDidLoad中self.view.bounds的值。并且不要忘记您需要实现各种表格视图数据源和委托方法。 -
顺便说一句 - 虽然可能与您的问题无关,但您的
loadView是不必要的。只需在viewDidLoad中设置背景颜色即可。 -
我更新了我的代码
-
您是否将
PlaygroundPage.current.liveView设置为您的控制器实例?
标签: ios swift uitableview swift-playground