2012-09-06 138 views
3

我在自定義單元格內有一個UIButton,我想在用戶按下該按鈕時觸發一個動作,但是我需要知道UIButton從哪一行被按下。將參數傳遞給選擇器

這裏是我的代碼:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 
    [self configureCell:cell atIndexPath:indexPath]; 
    return cell; 

    ... 

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

} 

- (void)buttonPressedAction:(UIButton *)button 
{ 
    //int row = indexPath.row; 
    //NSLog(@"ROW: %i",row); 
} 

如何通過indexPath作爲參數傳遞給我的選擇?

+0

http://stackoverflow.com/questions/7504421/getting-row-of-uitableview-cell-on-button-press/7505025#7505025 – user523234

回答

6

您可以將按鈕的標籤屬性設置爲行號:

button.tag = indexPath.row; 

,並使用

NSInteger row = button.tag; 

檢索或設置索引路徑對象本身作爲一個相關聯的對象到按鈕:

objc_setAssociatedObject(button, "IndexPath", indexPath); 

NSIndexPath *ip = objc_getAssociatedObject(button, "IndexPath"); 
+0

+1完美回答 –

+0

Downvoter:原因? – 2012-09-06 10:15:24

+0

謝謝!該按鈕的關聯對象看起來像一個優雅的解決方案 – Pupillam

2

,同時增加對自定義單元格按鈕,U可以添加的UIButton的tag財產

UIButton *sampleButton = [[UIButton alloc] init]; 
sampleButton.tag = indexPath.row; 

,然後當u打電話,U可以檢查標籤

- (void)buttonPressedAction:(UIButton*)sender 
{ 
    if(sender.tag==0) 
    { 
     //perform action 
    } 
} 

希望它有助於。快樂編碼:)

+0

你必須將按鈕聲明爲UIButton,否則屬性訪問器將不起作用。 (我沒有-1,順便說一句)。 – 2012-09-06 10:07:48

+0

我已經宣佈該按鈕爲UIButton .. –

+0

不,您的發件人對象在此答案中是'id'類型。 – 2012-09-06 10:22:46

1

簡單的設置按鈕標籤..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 
    [self configureCell:cell atIndexPath:indexPath]; 
    return cell; 

    ... 

    [button setTag = indexPath.row]; // Set button tag 

    [button addTarget:self action:@selector(buttonPressedAction:) 
              forControlEvents:UIControlEventTouchUpInside]; 
    } 

    - (void)buttonPressedAction:(id)sender 
    { 
     UIButton *button = (UIButton *)sender; 
     int row = [button superview].tag; 
    } 
} 
1

它甚至比設置變量簡單。試試這個..

要得到indexPath,請嘗試下面的代碼。

UIView *contentView = (UIVIew *)[button superview]; 
UITableViewCell *cell = (UITableViewCell *)[contentView superview]; 
NSIndexPath *indexPath = [self.tableview indexPathForCell:cell]; 

OR

NSIndexPath *indexPath = [self.tableview indexPathForCell:(UITableViewCell *)[(UIVIew *)[button superview] superview]];