I have several tables the default cells such as the one with title, or the one with icon on the left and title on the right.
I don't want to add those cells in storyboard and assign identifier to them, is it possible to do that?
it has to be reusable, I know how to alloc new non-reusable cells
I have tried the answers below,
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:MyCellIdentifier];
should be correct, but it's very tedious and easily forget
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
The above maybe better since it puts all the codes at one place, but when I try dequeueReusableCellWithIdentifier:forIndexPath: (with indexPath) it crashes.
If you don't have any prototype cell in your storyboard, you can use the dequeueReusableCellWithIdentifier: api to create classic cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; }
swift:
var cell : UITableViewCell! cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier) }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = { guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else { return UITableViewCell(style: .default, reuseIdentifier: "cell") } return cell }() cell.textLabel?.text = anyArray[indexPath.row] return cell }
It is good, because give cell unwrapped.
You can dequeue a UITableViewCell without having a prototype cell in your storyboard. You need to register the cell with your table for a specific identifier (string). You would do this like so:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:MyCellIdentifier];
You could do this in viewDidLoad
, maybe.
Then, you can dequeue a cell using that identifier in your cellForRowAtIndexPath
method as usual.
Edit:
Where MyCellIdentifier
is a constant you have defined somewhere, of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With