如何在 swift 中创建 UITableView

How to create a UITableView in swift

我正在尝试在 Swift 中创建一个 UITableView。我遵循了一个教程,但是 table 没有我尝试在代码中放入的值。这是代码:

class settingsVC2: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var tableView: UITableView!
    var items: [String] = ["We", "Heart", "Swift"]

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

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

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("You selected cell #\(indexPath.row)!")
    }
}

您必须将 table(委托和数据源)连接到 ViewController 本身。

或者您可以通过将以下行添加到您的 viewDidLoad() 中以编程方式完成此操作:

    self.tableView.dataSource = self
    self.tableView.delegate = self