Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More than one custom cell with in the same XIB

Is it possible to have more than one custom uitableviewCell within the same xib?

I'm trying to save XIB files by combining different customized cells within the same xib and then having the Table load different ones from it.

In IB, I tried setting each of the uiTableViewCell class to a different custom class .m/.h implementation. Here is what I tried:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *cellIdentifier = @"DevConfigCell";

DeviceInfoCell *cell = (DeviceInfoCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if(cell == nil)
{

    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell~iphone" owner:self options:nil];
    cell = ( DeviceInfoCell *)[nib objectAtIndex:0];

}

return cell;
}

In another table, i would reuse the nib, but i would do this:

    cell = ( SecondDeviceInfoCell *)[nib objectAtIndex:0];

For some reason it always loads the first cell.

Should this all work? or is there a way?

Thanks

like image 395
mskw Avatar asked Oct 06 '22 19:10

mskw


1 Answers

I'm trying to save XIB files by combining different customized cells within the same xib

Why? There's no limit on the number of .xib files you can create.

and then having the Table load different ones from it.

When you load a .xib, all the objects that file contains are created. If you put 10 custom cells in one .xib, loading that .xib will create an instance of each of those 10 cells. That's probably not what you want. Keeping your cells in separate .xibs is probably a better plan.

cell = ( SecondDeviceInfoCell *)[nib objectAtIndex:0];

You seem to be confused about what casting does. When you cast from one type to another, you're not somehow selecting a different object. The object returned by [nib objectAtIndex:0] is always going to be the same if the nib array has the same contents. Casting just changes the type that the compiler associates with the value; in this case it changes the type of the pointer.

You can create an IBOutletCollection in your view controller and then connect several different custom cells to that outlet collection; that'll give you an array of cells that you can select from using objectAtIndex:. But again, that's really not a good idea since you'll be creating all the cells in the file every time you need just one.

like image 170
Caleb Avatar answered Oct 10 '22 02:10

Caleb