Hello everyone,
I am trying to add custom button with tag related to indexPath.row. I can view the tag value correctly if I don’t insert new row into tableview. But, when I insert new row, my tag value of new row is not correct if the inserted row is not within 0 to 9 (iphone 5 can show up to that). On iphone, I need to scroll down to see.
However, with the same code, I can get my tag value correctly on my ipad. I don’t need to scroll down table view on my ipad to see all my row.I would like to know why it happen and how to solve.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"dialoguesTableCell";
dialoguesCell *cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[dialoguesCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
[yourButton setImage:[UIImage imageNamed:@"1StarBlank.png"] forState:UIControlStateNormal];
[yourButton setTitle:@"Button" forState:UIControlStateNormal];
[yourButton addTarget:self action:@selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside];
yourButton.tag=indexPath.row;
yourButton.frame = CGRectMake(5, 10, 40, 25);
[cell addSubview:yourButton];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *indexPathstoinsert = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:section];
NSArray *indexPathsToInsertArray = [NSArray arrayWithObject:indexPathstoinsert];
[[self mainTableView] insertRowsAtIndexPaths:indexPathsToInsertArray withRowAnimation:UITableViewRowAnimationRight];
}
this is not working correctly because the UITableView reuses cells
when you scroll down, the first cells arent visible anymore and are reused.
if the table is .. ‘small’ you can just work around it by not reusing cells
BUT if the table isnt just a few entries but a lot of data you really want to change your way
assign the tag for the button in:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPathe.g.
in the commment you mentioned another problem: the buttons are hidden in your
didSelectRowmethod and are then gone from other cells too after scrolling. SAME issue: the cell objects are REUSED by the tableview. dont store state in reusable cells!Instead have a ‘model’ tree or array that remembers the state : text, image, tag, hide:yes/no
NSArray *myTableContentsTHEN always use THAT array in numberOfRows and in viewForRow and modify it in didSelectEntry