簡體   English   中英

具有自定義數據源的UITableViewController不顯示單元格

[英]UITableViewController with custom data source not showing cells

我目前有一個UITableViewController,它在其init函數中設置了一個自定義數據源:

class BookmarkTableViewController: UITableViewController {
  var date: Date

  // MARK: - Init
  init(date: Date, fetchAtLoad: Bool) {
    self.date = date
    super.init(style: .plain)
    self.tableView.dataSource = BookmarkDataSource(date: date)
    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
  }

// ...
}

定制數據源如下:

class BookmarkDataSource: NSObject {
  let date: Date

  init(date: Date) {
    self.date = date
    super.init()
  }
}

// MARK: - UITableViewDataSource
extension BookmarkDataSource: UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = "Test content"

    return cell
  }
}

但是,當我在模擬器或設備上運行時,表視圖中沒有任何顯示。 有人知道我在想什么嗎?

注意:我正在使用Xcode 8.0 Beta和Swift 3。

您需要存儲對BookmarkDataSource對象的強引用。 tableView的dataSource與您發布的代碼一起變為nil。

class BookmarkTableViewController: UITableViewController {
    var date: Date
    var dataSource:BookmarkDataSource

    // MARK: - Init
    init(date: Date, fetchAtLoad: Bool) {
        self.date = date
        super.init(style: .plain)
        dataSource = BookmarkDataSource(date: date)
        self.tableView.dataSource = dataSource
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    // ...
}

我認為您的單元格未正確實例化。

嘗試更換

let cell = UITableViewCell()

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

暫無
暫無

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

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