2010-09-17 54 views
2

我在我的cellForRowAtindexPath上有这个代码,每个单元格上有一个自定义的单元格和一个按钮。帮助button.tag = indexPath.row

 
- (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(也许button.tag等于0时,它必须在14?)

+0

看看类似的问题:http://stackoverflow.com/questions/1802707/detecting-which-uibutton-was-pressed-in-a-uitableview – Vladimir 2010-09-17 11:22:24

+0

谢谢......我已经解决了这个问题: – david 2010-09-17 12:15:26

回答

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); 

}

这对我的作品。

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

你不能接受你的答案? – mxg 2011-06-22 12:02:21

+0

@david感谢您发布此!它为我节省了很多时间。 – user3079872 2015-07-16 09:37:35