我使用nib文件创建了UItableViewCell,并在我的单元格中添加了一个按钮。当用户点击按钮时,我创建了一个IBAction来关联一个动作。但是我遇到了崩溃,我不知道它是什么问题,我已经设置了所有必要的东西。
//in my .h
-(IBAction)go;
//in my .m
-(IBAction)go
{
NSLog(@"hello");
}
但我发生了崩溃,在consol调试中没有显示任何内容。
如何在UITableviewcell中设置按钮并将此按钮与操作相关联。谢谢你的回答
答案 0 :(得分:10)
在我看来,设置标签是一种糟糕的方式。它限制了应用程序中其他地方的Tag的更好用法。
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
使用这种方法,您实际上可以检索单元格的IndexPath。
答案 1 :(得分:1)
以编程方式创建按钮并将其添加到单元格的子视图中。将tag设置为indexPath.row值并将target添加到按钮。现在在目标中你可以简单地使用:
-(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
}
答案 2 :(得分:1)
这对我有用......
- (void)yourButton:(id)sender{
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
CustomCellClass *cell = (CustomCellClass *)[self.tableView cellForRowAtIndexPath:indexPath];
NSString *myFooText = cell.cellLabelFoo.text;
}
答案 3 :(得分:0)
以编程方式创建按钮并将其添加到单元子视图。
答案 4 :(得分:0)
您可以使用此代码在不使用nib的情况下以编程方式将IBAction与按钮相关联:
[myButton addTarget:self action: @selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
答案 5 :(得分:0)
崩溃可能是由于以下原因
如果您发布了一些关于如何创建单元格的代码,您将能够获得有关它的更多信息。
答案 6 :(得分:0)
你需要制作一个方法并将(id)发送者传递给它; 试试这个..希望这个有用..这就是你写的按钮和调用方法的地方..
[myButton addTarget:self action: @selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
-(void)buttonPressed:(id)sender{
nslog(@"hi");
}
希望这有效