[英]Xib file UITableViewCell outlets are nil
This is a bit of an ongoing topic, but my situation is slightly different.这是一个持续的话题,但我的情况略有不同。 I'm working with this tutorial .我正在使用本教程。 I have a view controller, that has it's own storyboard, this view controller has table view.我有一个视图 controller,它有自己的 storyboard,这个视图 controller 有表格视图。 The view controller is this table's delegate and data source.视图 controller 是该表的委托和数据源。 I need to add different kinds of cells to this table, and I'm using cell view model as well for this.我需要向该表中添加不同类型的单元格,并且为此我也使用了单元格视图 model。
Cell:细胞:
class TitleTextCell: UITableViewCell, CellConfigurable {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var textView: UITextView!
static let identifier = "TitleTextCell"
func setup(viewModel: RowViewModel) {
guard let titleTextViewModel = viewModel as? TitleTextViewModel else {return}
titleLabel.text = titleTextViewModel.title //fatal: found nil while
textView.text = titleTextViewModel.text //unwrapping an optional value
}
}
Table view controller's ViewController:表视图控制器的 ViewController:
class InfoViewController: UIViewController, Storyboarded {
// MARK: - Properties
var viewModel: InfoViewModelType! {
didSet {
viewModel.viewDelegate = self
}
}
// MARK: - Outlets
@IBOutlet weak var tableView: UITableView!
// MARK: - Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TitleTextCell.self, forCellReuseIdentifier: TitleTextCell.identifier)
tableView.delegate = self
tableView.dataSource = self
}
}
extension InfoViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.tableRows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let rowViewModel = viewModel.tableRows[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier(for: rowViewModel), for: indexPath)
if let cell = cell as? CellConfigurable {
cell.setup(viewModel: rowViewModel)
}
return cell
}
private func cellIdentifier(for viewModel: RowViewModel) -> String {
switch viewModel {
case is TitleTextViewModel:
return TitleTextCell.identifier
default:
fatalError("Unexpected view model type: \(viewModel)")
}
}
}
The cell is a xib file.该单元格是一个 xib 文件。 Outlets are connected with the file owner (see screens).出口与文件所有者相连(见屏幕)。
It does arrive at the point of func setup(viewModel: RowViewModel)
which means table-wise it's correct.它确实到达了func setup(viewModel: RowViewModel)
的点,这意味着在表格方面它是正确的。 But the outlets are nil at runtime, what am I missing?但是在运行时出口为零,我错过了什么?
You need你需要
tableView.register(UINib(nibName: "TitleTextCell", bundle: nil), forCellReuseIdentifier: TitleTextCell.identifier)
For xib cells对于 xib 细胞
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.