Reputation: 821
I have some custom UITableViewCell,and would using some of them randomly. But after I register them ,it will crashed in tableView(_cellForRowAt:)
.
Here is my code:
in viewDidLoad method
tableView.register(CustomACell.self, forCellReuseIdentifier: "Identifier")
tableView.register(CustomACell.self, forCellReuseIdentifier: "Identifier")
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = dataSource[indexPath.row]
if let type = model.type {
switch type {
case .A:
let cell = tableView.dequeueReusableCell(withIdentifier: MyIdentifier) as! CustomACell
cell.assgin(message: model)
return cell
case .B:
let cell = tableView.dequeueReusableCell(withIdentifier: MyIdentifier) as! CustomBCell
cell.assgin(message: model)
return cell
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: MyIdentifier) as! CustomACell
cell.assgin(message: model)
return cell
}
If I register both ,it will crashed at case .A. If I won't, some of them would crash at tableView.dequeueReusableCell
.
Here is one of the console error info:
Could not cast value of type 'TM.CustomACell' (0x10bb40940) to 'TM.CustomBCell' (0x10bb40578).
Upvotes: 1
Views: 122
Reputation: 856
if you created a separate Nib
, then you can register else no need to register
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell{
var cell = UITableViewCell(style: .default, reuseIdentifier: "pgIdentifier")
if (XXX == true) {
let pgtcell = tableView.dequeueReusableCell(withIdentifier: "indetifier", for: indexPath) as! CustomCell1
} else {
let pgtcell = tableView.dequeueReusableCell(withIdentifier: "indetifier", for: indexPath) as! MyCustomCell1
}
}
Upvotes: 1
Reputation: 1215
Change the CellReuseIdentifiers. You use same for both custom cells. Use diffrent identifires for diffrent cells.
var nibName = UINib(nibName: "Identifier1", bundle: nil)
self.tableView.register(nibName, forCellReuseIdentifier: "Identifier")
nibName = UINib(nibName: "Identifier2", bundle: nil)
self.tableView.register(nibName, forCellReuseIdentifier: "Identifier2")
Then change the cellForRowAt, try following code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = dataSource[indexPath.row]
if let type = model.type {
switch type {
case .A:
let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier1") as! CustomACell
cell.assgin(message: model)
return cell
case .B:
let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier2") as! CustomBCell
cell.assgin(message: model)
return cell
default :
let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier1") as! CustomACell
cell.assgin(message: model)
return cell
}
}
}
Upvotes: 3