簡體   English   中英

在靜態表格視圖中重用表格單元 - iOS - Swift

[英]Reuse tablecell in static table view - iOS - Swift

我是新手,學習很快

我想在我的表格視圖中使用靜態單元格。 我讓所有單元格看起來都相似,所以我想使用 xib 作為表格單元格並在我的靜態表格視圖中使用它。

我目前面臨的問題是,當我嘗試訪問我在 xib 中的標簽時,在方法中拋出錯誤:ConfigureCell 在下面的代碼中。 線程 1:致命錯誤:在隱式解包可選值時意外發現 nil 為什么在我沒有可選值時說我正在解包可選值

不確定這里需要做什么/請指教。

下面是我的代碼:

class NewTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

       self.tableView.register(ReusableTableViewCell.self, forCellReuseIdentifier:"custom")
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 4
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "custom", for: indexPath) as? ReusableTableViewCell else {
            return UITableViewCell()
        }
        if indexPath.row == 0 {
            cell.configureCell(title: "Name", detail: "hello")
        }
        if indexPath.row == 2 {
            cell.configureCell(title: "Age", detail: "23")
        }
        if indexPath.row == 3 {
            cell.configureCell(title: "Dept", detail: "HR")
        }
        return cell
    }
}

class ReusableTableViewCell: UITableViewCell {

@IBOutlet weak var leftLabel: UILabel!
@IBOutlet weak var rightLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

func configureCell(title: String, detail: String) {

    leftLabel.text = title //Error Here: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

    rightLabel.text = detail

}

} 在此處輸入圖片說明

找到了解決方案。 問題在於 self.tableView.register(ReusableTableViewCell.self, forCellReuseIdentifier:"custom")

用 tableView.register(UINib(nibName: "ReusableTableViewCell", bundle: nil), forCellReuseIdentifier: "custom") 替換它解決了這個問題

謝謝

暫無
暫無

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

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