0

I have a simple UITableView not scrollable and with no need to reuse cells. I have a custom cell class with a .xib file.

My goal is to pass the index path with a custom init inside the protocol method

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

when I create the custom cells in order to use the indexPath inside my customCellClass.m

Is there any way to achieve that?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Talkanian
  • 19
  • 1
  • 5
  • 4
    There is no valid reason a cell should know its `indexPath`. – rmaddy Feb 04 '16 at 16:41
  • I agree with rmaddy, this smells bad. If you need your cells to look differently depending on their index path, I suggest changing what needs to be changed in cellForRowAtIndexPath instead of letting the cell know about it. – Daniel Larsson Feb 04 '16 at 16:54
  • Maybe explain why you want to do this, there may be a better way of achieving your goal.. – matt_roo Feb 04 '16 at 17:05
  • Why don't you reuse the index path ? If you don't want your table to scroll and don't want to reuse the cells, then don't create a tableview. design your own custom view. – AskIOS Feb 05 '16 at 14:54
  • I need to do that because i have got an array with some objects. Each cell needs to listen for events of those objects, representing their data on the table view. So each cell needs to know his index to catch the right object notification by the object index. Sorry for my bad english. – Talkanian Feb 09 '16 at 08:02
  • It has some usage. If you want to create custom buttons in cell then if they are reused you need to know each cell's custom button has been clicked. Of course you can have Detail Disclosure or something similar but they have limited look. If you want to create custom button ex. down chevron for collapsing you need to pass indexPath on cell. – Michał Ziobro Feb 24 '18 at 18:03

1 Answers1

1

In your custom cell you can define an NSIndexPath property. When constructing the cell in cellForRowAtIndexPath you can set that property with the given index.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomTableViewCell" forIndexPath:indexPath];

    // This sets your custom indexPath property
    cell.indexPath = indexPath;

    // More cell setup

    return cell;
}

This can be useful working with delegates for identifying the cell to handle, say, a button click inside the cell. More context here.

Community
  • 1
  • 1
ama1111
  • 569
  • 3
  • 10