2012-09-06 94 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]];