我是新人,学得很快
我想在表格视图中使用静态单元格。我有所有单元看起来类似,所以我想到使用xib for tablecell并在我的静态表视图中使用它。
我当前面临的问题是,当我尝试访问我在xib中的标签时,我在方法中抛出错误:在下面的代码中配置了CellCell。线程1:致命错误:意外地发现nil,同时隐式展开一个Optional值为什么当我没有一个时,我会说我是uncrapping可选的
不知道这里需要做什么/请咨询。
下面是我的代码:
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”)解决了这个问题
谢谢