2011-05-23 141 views
0

我想構建一個自定義表格視圖單元格,並在其中放置一個按鈕,當用戶單擊該按鈕以轉到某個方法時 - 該方法將知道哪個單元格按鈕被按下。iPhone - 從自定義單元格中捕捉UIButton觸摸事件

thx

+0

你是從IB創建一個UITableViewCell或programmaticaly? – klefevre 2011-05-23 13:02:10

+0

[檢測在UITableView中按下哪個UIButton]的可能重複(http://stackoverflow.com/questions/1802707/detecting-which-uibutton-was-pressed-in-a-uitableview) – Vladimir 2011-05-23 13:06:34

回答

0

您可以給按鈕一個標籤。如果將此標記設置爲單元格indexPath.row的數量,則可以始終通過檢索標記Value來確定單擊了哪個單元格。

按鈕標記必須是一個整數btw,但母豬是indexPath.row。

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    Huis *h = [woningen objectAtIndex:indexPath.row]; 
    static NSString *identifier = @"Woning"; 
    WoningTableCell *cell = (WoningTableCell *)[tableView dequeueReusableCellWithIdentifier:identifier]; 
    if (cell == nil) { 
     cell = [[[WoningTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease]; 
    } 
    [cell setNewWoning:h withIndex:indexPath.row]; 
    return cell; 
} 

這裏我創建了一個自定義單元格,顯示'Huis'的詳細信息。當爲單元格設置對象時,我還會傳遞我正在填充的單元格的indexPath.row。

然後在自定義單元格,在設定目標,我還爲我的按鈕,這樣的標籤值:

UIButton *indexBtn = [UIButton .... ]; 
indexBtn.tag = indexRowInteger; 

的按鈕可能已創建/初始化,在這種情況下,你只設置標籤。現在,在功能處理您的ControlEvent資料你可以訪問此標籤,像這樣:

- (void) CellButtonPressed: (id) sender{ 

UIButton *b = ((UIButton *)sender); 
NSInteger tagValue = btn.tag; 

} 
4
- (void) cellButtonClicked: (id) sender 
{ 
  UIButton *btn = (UIButton *) sender; 
  UITableViewCell *cell = (UITableViewCell *) [[btn superview] superview]; 
  NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
  //do something with indexPath... 
} 

希望這項工作

相關問題