2

我使用 nib 文件创建了 UItableViewCell,并在我的单元格中放置了一个按钮。当用户单击按钮时,我创建了一个 IBAction 来关联一个动作。但是我崩溃了,我不知道这是什么问题,我已经设置了所有必要的东西。

//in my .h
-(IBAction)go; 

//in my .m
-(IBAction)go 
{ 
    NSLog(@"hello");
} 

但我发生了崩溃,consol 调试中没有显示任何内容。

我如何在 UITableviewcell 中设置一个按钮并与该按钮关联一个动作。感谢您的回答

4

7 回答 7

10

在我看来,设置标签是一种糟糕的方式。它限制了标签在应用程序其他地方的更好使用。

NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];

使用这种方法,您实际上可以检索单元格的 IndexPath。

于 2012-02-06T12:52:29.107 回答
1

以编程方式创建一个按钮并将其添加到单元格的子视图中。将 tag 设置为 indexPath.row 值并将目标添加到按钮。现在在目标中,您可以简单地使用:

 -(void)buttonInsideCellIsPressed : (id)sender{
   UIButton *button = (UIButton *)sender; 
   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
   CustomCell *cell = (CustomCell*)[myTable cellForRowAtIndexPath:indexPath];

   // Here you may change the background image for the button for rollover or anything 
    }
于 2011-05-12T17:22:44.007 回答
1

这对我有用...

- (void)yourButton:(id)sender{

    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    CustomCellClass *cell = (CustomCellClass *)[self.tableView cellForRowAtIndexPath:indexPath];

    NSString *myFooText = cell.cellLabelFoo.text;
}
于 2013-02-27T03:48:42.973 回答
0

以编程方式创建一个按钮并将其添加到单元格子视图中。

于 2011-05-03T12:31:10.010 回答
0

您可以使用以下代码以编程方式将 IBAction 与按钮相关联,而无需使用 nib:

[myButton addTarget:self action: @selector(buttonPressed) 
                 forControlEvents:UIControlEventTouchUpInside];
于 2011-05-03T12:40:41.070 回答
0

崩溃可能是由于以下原因

  1. 您已将视图控制器添加到您的单元格并释放它。因此,当点击按钮时,它无法找到控制器来处理点击
  2. 为点击事件添加按钮回调时,您没有指定有效的选择器
  3. 您可能正在访问为 NULL 的数据

如果您发布一些有关如何创建单元格的代码,您将能够获得有关它的更多信息。

于 2011-05-03T13:14:19.283 回答
0

您需要创建一个方法并将 (id )sender 传递给它;在下面试试这个..希望这有效..这个你写在按钮和调用方法的顶部..

[myButton addTarget:self action: @selector(buttonPressed:) 
                 forControlEvents:UIControlEventTouchUpInside];



-(void)buttonPressed:(id)sender{

nslog(@"hi");
}

希望这有效

于 2011-05-03T13:19:30.913 回答