Stan
Stan

Reputation: 6571

custom UITable cell how to build with unique included object state?

So I has custom table cell defined via builder and loaded via nib (and it has a property of its idexPath) and it has 2 buttons. I want to show table with dynamically changed state of those buttons. IE 1st cell - both enabled, 2nd cell - both buttons disabled, 3rd - 1st btn enabled and 2nd btn disabled and so on.
Now if I use 1 reuse identifier all the cells will look the same which I don't want. I want every cell has its own view which means unique reuse id for every cell.
But how to reach this? If I'll create some unique cellId at

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

which will be a string then I could not create the same string in meaning of objects. I could create string with same text but this will be another object so I couldn't get the previously created cell with such cellId again via reuseId. So i cant change buttons state of one cell and update it then with

[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationNone];

but only the [tableView reloadData]; will work.

Upvotes: 0

Views: 125

Answers (1)

sgress454
sgress454

Reputation: 24958

I have a feeling that you're only setting the state of your cell's buttons when you first create the cell with initWithStyle:reuseIdentifier:. This is the wrong way to go about things. You need to set the state for your cells in every call to cellForRowAtIndexPath, whether they're being re-used or not. In your case, if each cell has the same UI (two buttons) then they should all share one reuseIdentifier. Your datasource should be responsible for maintaining you cells' states, not the UITableViewCell objects.

It's the difference between this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     myCustomCell *cell = (myCustomCell *)[myTable dequeueReusableCellWithIdentifier:@"myCellIdentifier"];
     if (cell == nil) {
       // Load cell from nib here and set the cell's button states based on indexPath
     }
    return cell;
}

and this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     myCustomCell *cell = (myCustomCell *)[myTable dequeueReusableCellWithIdentifier:@"myCellIdentifier"];
     if (cell == nil) {
       // Load cell from nib here
     }
    // set the cell's button states based on indexPath here
    return cell;
}

Upvotes: 1

Related Questions