简体   繁体   English

Swift 表视图未显示内容

[英]Swift table view not showing contents

I wanted to give a go at swift, and looked at several tutorials.我想在 swift 上给一个 go,看了几个教程。 I tried to implement a TableView.我试图实现一个 TableView。

Here is my code:这是我的代码:

import UIKit

class ViewController:  UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var items: [String] = ["lol1", "lol2", "lol3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

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

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")!

        cell.textLabel?.text = self.items[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        print("You selected cell #\(items[indexPath.row])!")
    }

}

MY IBOutlet is connect to the tableview I inserted in the storyboard.我的 IBOutlet 连接到我在 storyboard 中插入的 tableview。

When I run it, I have a TableView, but it's missing contents.当我运行它时,我有一个 TableView,但它缺少内容。

From what I gathered through some (more or less outdated) tutorials, I shouldn't have anything more to do, what am I missing?从我通过一些(或多或少过时的)教程收集的内容来看,我不应该做更多的事情,我错过了什么?

Where are you set dataSource and Deleagte methods of TableView?你在哪里设置 TableView 的 dataSource 和 Deleagte 方法?

use this code使用此代码

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

2 possible reasons: 2个可能的原因:

  1. If the cell is designed as prototype cell you must not register the cell.如果单元设计为原型单元,则不得注册该单元。
  2. dataSource and delegate of the table view must be connected to the controller in Interface Builder or set in code.表格视图的dataSourcedelegate必须连接到Interface Builder中的controller或在代码中设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM