繁体   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