Talkanian
Talkanian

Reputation: 29

How to pass indexPath to a CustomCell

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?

Upvotes: 0

Views: 230

Answers (1)

ama1111
ama1111

Reputation: 579

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.

Upvotes: 1

Related Questions