我正在为我的UITableViewCell
添加自定义按钮。 在该按钮的操作中,我想调用showAlert:
函数,并希望在方法中传递单元格标签。
如何在action:@selector(showAlert:)
方法中传递参数?
我正在为我的UITableViewCell
添加自定义按钮。 在该按钮的操作中,我想调用showAlert:
函数,并希望在方法中传递单元格标签。
如何在action:@selector(showAlert:)
方法中传递参数?
如果您在Tableviewcell中使用按钮,则必须为每个单元格的按钮添加标记值,并设置方法addTarget并将id作为参数。
示例代码:
您必须在cellForRowAtIndexPath
方法中输入以下代码。
{
// Set tag to each button
cell.btn1.tag = indexPath.row;
[cell.btn1 setTitle:@"Select" forState:UIControlStateNormal]; // Set title
// Add Target with passing id like this
[cell.btn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
-(void)btnClick:(id)sender
{
UIButton* btn = (UIButton *) sender;
// here btn is the selected button...
NSLog(@"Button %d is selected",btn.tag);
// Show appropriate alert by tag values
}
这是不可能的。您必须创建一个符合IBAction的方法。
- (IBAction)buttonXYClicked:(id)sender;
Jay的答案很棒,但如果你有多个部分,它将不起作用,因为indexRow是local to a section。
另一种方法是,在使用具有多个部分的TableView中的按钮时,传递触摸事件。
在惰性加载器中声明按钮的位置:
- (UIButton *)awesomeButton
{
if(_awesomeButton == nil)
{
_awesomeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_awesomeButton addTarget:self.drugViewController action:@selector(buttonPressed:event:) forControlEvents:UIControlEventTouchUpInside];
}
return _awesomeButton;
}
- (void)buttonPressed:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
NSLog(@"Button %d was pressed in section %d",indexPath.row, indexPath.section);
}
indexPathForRowAtPoint
。这是UITableView
中一个非常方便的函数,可以在任何点给出indexPath。同样重要的是函数locationInView
,因为您需要在tableView上下文中找到触摸点,以便确定特定的indexPath。