自定义uitaiteViewCell和Ibaction
-
29-09-2019 - |
题
我有一个自定义的uitableviewcell,我在上添加了一个按钮,我在ibaction上将该按钮关联到了viewController中。现在,我面临的问题是我如何知道创建该按钮的哪个单元格。当我介绍其中包含一个表并具有多个行(自定义uitaiteViewCell)的ViewController时,现在用户按下按钮时,该操作被调用了,但是我怎么知道是哪一行。
因为基于行索引,我需要存储一些值。
编辑:我现在有一些线索,但是我仍然不确定我该怎么做,所以在我的tableviewController cellforrowatIndExpath上,我必须做这样的事情
[cell.button1 addTarget:self action:@selector(addToCart:) forControlEvents:UIControlEventTouchUpInside];
然后我必须写一个方法
-(IBAction) addToCart:(id) sender
但是我仍然不知道如何在AddTocart方法中获取行索引。感谢你的帮助。
解决方案
好的,终于我得到了答案,研究了不同的论坛,人们建议这样做这样的事情
在CellForrowatIndExpath中的自定义表视图控制器中
cell.addToCart.tag = indexPath.row;
[cell.addToCart addTarget:self action:@selector(addToCart:)
forControlEvents:UIControlEventTouchUpInside];
在我的CustomutableViewCell中,AddTocart是Uibutton的名称。它似乎对我不起作用。所以这就是我所做的
-(IBAction) addToCart:(id) sender{
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)
[[sender superview] superview]];
NSLog(@"The row id is %d", indexPath.row);
}
然后,通过InterfaceBuilder I将按钮的动作与表视图控制器上的添加ibaction相关联。
其他提示
少得多。
[cell.button1 addTarget:self action:@selector(addToCart:event:) forControlEvents:UIControlEventTouchUpInside];
- (void)addToCart:(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];
}
公认的答案不再起作用。请参阅 这 邮政
它这样做:
- (void)checkButtonTapped:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
if (indexPath != nil)
{
...
}
}
许多开发人员使用自定义视图在旧版本的iOS上显示自定义单元格。如果您是其中之一,那么您将必须面对一个问题,即您的按钮点击操作将不再使用iOS7。
如何解决这个问题:
您有两个选择:
选项1: :创建使用新的表单元格而不是视图创建新的布局。并将所有布局再次放在表单元格中。
我知道,这将需要大量的努力。如果您不想这样做,我们对此有很小的黑客攻击:选项2
选项2: :为您的按钮创建一个IBOUTLET,并添加此按钮作为单元格内容视图的子视图。
[self.myCell.contentView addSubview:self.btn_click];
上面的代码行将添加BTN_Click作为您的内容视图的子视图。现在,按钮点击操作应起作用。