I have the following code used to display some user information as well as a ‘invite’ button in a table cell. I am however not sure how I can access the cell’s information e.g. user again when I click on the invite button (in ‘inviteButtonPressed’ method) since I am unable to pass any parameters to the button click method. Can anyone advise me how I can access the cell’s information in the button click method?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* PlaceholderCellIdentifier = @"SectionsTableIdentifier";
GenericUser *user = [userSection objectAtIndex:row];
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
cell.textLabel.textColor = [UIColor darkGrayColor];
UIButton *inviteButton = [self setupButtonWithTitle:@"Invite" andFrame:CGRectMake(224, (44-24)/2, 56, 24)];
[inviteButton addTarget:self action:@selector(inviteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
inviteButton.tag = 1;
[cell.contentView addSubview:inviteButton];
}
UIButton *thisInviteButton = (UIButton*)[cell.contentView viewWithTag:1];
//This is where I will trigger the button press method
[thisInviteButton addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
UILabel *thisInvitedLabel = (UILabel*)[cell.contentView viewWithTag:2];
cell.textLabel.text = user.name;
cell.detailTextLabel.text = user.email;
if (user.isSelected)
{
thisInviteButton.hidden = YES;
}
else
{
thisInviteButton.hidden = NO;
}
return cell;
}
-(void)inviteButtonPressed:(id)sender
{
//I want to access the cell information here. How can I do it? Basically I want to pass the user information belonging to the cell to this method
}
You could subclass UIButton and add a property (let’s call it selectedIndexPath) to hold an NSIndexPath. Instead of an UIButton you place your subclass on the cell and set the index path after the line
MyButton *thisInviteButton = (MyButton *)[cell.contentView viewWithTag:1];than you can do
or another approach, without the need of custom buttons:
I am not sure, what approach I find less ugly.