2011-02-17 23 views
0

我做了一個表,內容有一些價值觀,我有一個按鈕編碼像如何通過單擊按鈕(定位到方法)來獲取特定行的索引?

cell.textLabel.textColor = [UIColor whiteColor]; 

UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom]; 
[btn setBackgroundColor:[UIColor clearColor]]; 
[btn setBackgroundImage:[UIImage imageNamed:@"edit_button.png"] forState:UIControlStateNormal]; 
[btn setFrame:CGRectMake(290, 15, 15, 15)]; 
[btn addTarget:self action:@selector(editTable:) 
     forControlEvents:UIControlEventTouchUpInside]; 
[cell.contentView addSubview:btn]; 

NSString *cellValue = [myArrayNew objectAtIndex:indexPath.row]; 
cell.textLabel.text = cellValue; 

return cell; 

我想點擊該按鈕,並從該特定指數取值,

阿里(按鈕在這裏)--------索引0 Sajid(button here)-------- index 1 Robert(button here)-------- index 2 RaM(button here )-------- index 3

Theser是表的單元格,現在如何獲取索引,因爲我單擊該按鈕?

,如果你沒有得到我的問題,你可以再問我......

+0

可能重複http://stackoverflow.com/questions/1802707/detecting-which-uibutton-was-pressed-in -a-uitableview) – Vladimir 2011-02-17 09:47:55

回答

2

我發現我的答案,

只寫按鈕針對性的方法中採用下列代碼,並使用clickButtonPath作爲索引路徑。 它可以正常使用,只需

UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview]; 
NSIndexPath *clickedButtonPath = [self.tableView indexPathForCell:clickedCell]; 
[檢測其中的UIButton在一個UITableView壓](的
0
btn.tag = indexPath.row; 

然後在(void)editTable:(id)sender

int row = (UIButton *)btn.tag; 
+0

但是如果它在btn中保存一個值,那麼就不會刪除它,即使我點擊了其他按鈕,現在該怎麼辦? – 2011-02-17 09:57:28

0

你會使用這樣的事情。

- (IBAction)editTable:(UIButton *)sender { 
    UIView *contentView = [sender superView]; 
    UITableViewCell *cell = [contentView superView]; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
} 

但首先你應該確保正確地重用你的單元格。通過改變你的代碼是這樣的:

cell = ... dequeue cell ... 
if (cell == nil) { 
    cell = ... create new cell ... 
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom]; 
    btn.tag = 194; 
    [btn setBackgroundColor:[UIColor clearColor]]; 
    [btn setBackgroundImage:[UIImage imageNamed:@"edit_button.png"] forState:UIControlStateNormal]; 
    [btn setFrame:CGRectMake(290, 15, 15, 15)]; 
    [btn addTarget:self action:@selector(editTable:) 
     forControlEvents:UIControlEventTouchUpInside]; 
    [cell.contentView addSubview:btn]; 
} 
// if you need to change something for this button you can get it like this: 
//UIButton *btn= [cell.contentView viewWithTag:194]; 
NSString *cellValue = [myArrayNew objectAtIndex:indexPath.row]; 
cell.textLabel.text = cellValue; 

return cell; 
+0

錯誤在這裏「'*** - [UIButton superView]:無法識別的選擇器發送到實例0x393a5c0'」 – 2011-02-17 10:15:44

相關問題