簡體   English   中英

Swift 表視圖未顯示內容

[英]Swift table view not showing contents

我想在 swift 上給一個 go,看了幾個教程。 我試圖實現一個 TableView。

這是我的代碼:

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])!")
    }

}

我的 IBOutlet 連接到我在 storyboard 中插入的 tableview。

當我運行它時,我有一個 TableView,但它缺少內容。

從我通過一些(或多或少過時的)教程收集的內容來看,我不應該做更多的事情,我錯過了什么?

你在哪里設置 TableView 的 dataSource 和 Deleagte 方法?

使用此代碼

 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個可能的原因:

  1. 如果單元設計為原型單元,則不得注冊該單元。
  2. 表格視圖的dataSourcedelegate必須連接到Interface Builder中的controller或在代碼中設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM