知道选择哪个单元格的按钮

时间:2015-01-21 11:02:50

标签: objective-c uitableview uibutton

我有一个包含37个对象的数组,这个对象必须列在tableview单元格中。对于每个单元格,我创建了自定义按钮。所以37个按钮。对于每个按钮,我都给出了一个图像,就像复选框一样。如果选择了按钮,则图像会发生变化。现在我想知道单击哪个单元格的按钮。

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

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell..
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(34, 4, 300, 30)];
    label.text=[categoryarray objectAtIndex:[indexPath row]];
    [cell.contentView addSubview:label];
    UIButton *cellbutton=[[UIButton alloc]initWithFrame:CGRectMake(0, 10, 20, 20)];
    cellbutton.tag=[indexPath row];
    [cellbutton setBackgroundImage:[UIImage imageNamed:@"bfrtick.png"] forState:UIControlStateNormal];
    [cellbutton addTarget:self action:@selector(button1Tapped:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:cellbutton];
    return cell;
}

5 个答案:

答案 0 :(得分:2)

在cellforrowatindexpath中,

button.tag = indexpath.row
button.addTarget(self, action: Selector("FindTag:"), forControlEvents: UIControlEvents.TouchUpOutside)

目标方法

    @IBAction func FindTag(sender: UIButton) {
    let buttontag = sender.tag // it is the row where button is
    //Now you know which row contains the button.
}

答案 1 :(得分:1)

由于您已经在目标中标记了按钮,因此您可以使用发件人再次识别该按钮,例如

-(void) onButtonPressed:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSLog(@"%d", [button tag]);
}

答案 2 :(得分:1)

从按钮中,找到包含该按钮的单元格。从单元格中,您可以获取索引路径。从索引路径中,您可以获得数组索引。这将无需担心维护标签。

- (IBAction)button1Tapped:(UIButton *)button
{
    UIView *view = button;
    while (view && ![view isKindOfClass:[UITableViewCell class]]) {
        view = view.superview;
    }

    if (!view) {
        return; // The button was not in a cell
    }

    UITableViewCell *cell = (UITableViewCell *)view;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

    if (!indexPath) {
        return; // The cell was not in the table view
    }

    NSInteger arrayIndex = indexPath.row;
    …
}

顺便说一句,您的代码存在问题。当您重新使用重复使用的单元格时,它已经有一个标签和一个按钮。

您的代码只会将标签和按钮分层放在现有按钮和标签的顶部。这将导致问题。

答案 3 :(得分:0)

创建一个NSMutableDictionary或NSMutableArray,它将包含indexPath行(cellbutton.tag),然后您可以根据需要进行处理。如果你有每个单元格对象的id,那将是最好的,但这也可以。

另外,请记住,每个单元格都是可重用的,您必须检查数组中是否存在特定按钮。否则,您可能会显示不一致的图像。

答案 4 :(得分:0)

您可以为按钮设置标签

并且在touchUpInside处理程序中,您可以获取此标记,并通过此标记获取数据源中的所有数据,并考虑标记值是您的索引值。

例如: 在tableviewCellForRowAtIndexPath方法中:

button.tag = [indexpath row]; //assign current index value to your button tag

然后在你的touchUpInside处理程序

- (IBAction)buttonTuouchedUpInside:(id)sender {

   UIButton *button = (UIButton*)sender; // convert sender to UIButton

   NSInteger index = button.tag; // get button tag which is equal to button's row index 

   NSObject *myDataEntry = [myDataArray objectAtIndex:index] 

   //do something with this data
}
相关问题