单击单元格内容视图按钮后如何访问单元格信息?

时间:2012-01-08 00:32:26

标签: objective-c ios cocoa-touch uitableview uibutton

我有以下代码用于显示一些用户信息以及表格单元格中的“邀请”按钮。然而,我不知道如何访问单元格的信息,例如当我点击“邀请”按钮(在“inviteButtonPressed”方法中)时,再次使用用户,因为我无法将任何参数传递给按钮单击方法。谁能告诉我如何在按钮点击方法中访问单元格的信息?

- (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

}

1 个答案:

答案 0 :(得分:2)

您可以继承UIButton并添加一个属性(让我们称之为selectedIndexPath)来保存NSIndexPath。您将子类放在单元格而不是UIButton上,并在行MyButton *thisInviteButton = (MyButton *)[cell.contentView viewWithTag:1];

之后设置索引路径

比你能做的

-(void)inviteButtonPressed:(id)sender
{
    NSIndexPath *indexPath = [((MyButton *)b) selectedIndexPath];
    GenericUser *user = [userSection objectAtIndex:[indexPath row]];


}

或其他方法,无需自定义按钮:

-(void)inviteButtonPressed:(id)sender 
{
    UIButton *b = (UIButton *)sender;
    UITableViewCell* cell =  (UITableViewCell*)[[b superview] superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    GenericUser *user = [userSection objectAtIndex:[indexPath row]];

}

我不确定,我觉得哪种方法不那么难看。