关于button.tag = indexPath.row的帮助

时间:2010-09-17 10:53:41

标签: iphone uitableview

我的cellForRowAtindexPath上有这个代码,每个单元格上都有一个自定义单元格和一个按钮。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
 static NSString *MyIdentifier = @"tblCellView";

 TableCellView *cell = (TableCellView *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];

 Alarms *alarma = (Alarms *)[alarmsArray objectAtIndex: indexPath.row];

 if (!cell) {
  [[NSBundle mainBundle] loadNibNamed:@"TableCellView" owner:self options:nil];
  cell = tblCell;

  UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(-7, 4, 30, 33)];

  [button addTarget:self action:@selector(favButtonAction:) forControlEvents:UIControlEventTouchUpInside];
  [button setTag:1];
  [cell.contentView addSubview:button];

  [button release];
 }

 // Set up the cell.
 [cell setLabelText:  [alarma nombreAlarma]];

 UIButton *button = (UIButton *)[cell viewWithTag:1];

 button.tag = indexPath.row;

 return cell;
}

我的问题是,当我点击按钮时,我得到随机结果,一旦我移动到桌子上并且细胞重复使用,我得到的不同索引不等于所讨论的细胞的标签tex。


-(IBAction)favButtonAction: (id)sender
{
 UIButton *button = (UIButton *)sender; 

 Alarms *alarma = (Alarms *)[alarmsArray objectAtIndex: button.tag];

 NSLog(@"labelText: %@",[alarma nombreAlarma]);

}

例如,第一个单元格总是正常,但最后一个单元格等于第一个objectAtIndex(当它必须是14时,button.tag可能等于0?)

2 个答案:

答案 0 :(得分:2)

好的我找到了一个解决方案,这是一种不同的方法,但它有效:

[button addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];

然后在按钮处理程序上:

- (void)checkButtonTapped:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath != nil)
    {
     ...
    }
}

此处有更多信息Detecting which UIButton was pressed in a UITableView

答案 1 :(得分:1)

不要将按钮的标记值放在单元格内。

这是我单元格内容视图中的按钮。注意:按钮应该是Contentview的子视图。

[cell1.YourButton addTarget:self action:@selector(OnClickCategory:) forControlEvents:UIControlEventTouchUpInside];

按钮的操作

- (void) OnClickCategory:(id) sender {

//NSIndexPath *indexPath =(NSIndexPath *)[sender tag];

UIView *senderButton = (UIView*) sender;
NSIndexPath *indexPath = [CategoryTable indexPathForCell: (UITableViewCell*)[[senderButton superview]superview]];

NSLog(@"%d",indexPath.row);

}

这适合我。