I am putting together a TableView and I need to have multiple cell classes used in the same table.
So for example how would I use more than one cell class in my cellForRowAtIndexPath
method?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
return cell;
}
I know I could simply replace UITableViewCell
with my custom class and use if statements to adjust the class depending on the index, but isn't that a bit messy, what would be a reasonable, and possibly the most intelligent way of doing this?
Sure can. Just create new instances of your custom cells and give them a new CellId.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (condition1)
{
static NSString *CellIdentifier1 = @"Cell1";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
// TODO: if cell is null, create new cell of desired type.
// This is where you create your custom cell that is
// derived form UITableViewCell.
}
else
{
static NSString *CellIdentifier2 = @"Cell2";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
//TODO: if cell is null, create new cell of desired type
}
// Configure the cell...
return cell;
}
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