2010-09-17 67 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