ios - CellForRowAtIndexPath 中给出的 UIButton 标记仅给出自定义 UITableViewCell 中的最后一个标记值

标签 ios objective-c uitableview tableview

我有两个 UIButtonUITableViewCell子类,在 View Controller 类中我有它的选择器方法,但是在单击按钮时,它总是给出在 cellForRowAtIndexPath 内分配的最后一个标记值方法。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"cell";

    customCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    customCell.oneYear.tag = indexPath.row;

    customCell.threeYearButton.tag = indexPath.row + 50;
[customCell.oneYear addTarget:self
                    action:@selector(oneYearButtonAction)
          forControlEvents:UIControlEventTouchUpInside];

[customCell.threeYearButton addTarget:self
                       action:@selector(threeYearButtonAction)
             forControlEvents:UIControlEventTouchUpInside];

[customCell setSelectionStyle:UITableViewCellSelectionStyleNone];

如果我使用 IBAction,它工作正常,但我必须使用选择器方法,这会产生上述问题。

请帮忙。

最佳答案

您需要使用 cellForRowAtIndexPath 创建自定义类的新实例而不是你使用相同的实例 customCell .

而不是这个:

customCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

您需要像这样创建新对象:
CustomCellName *customCell = (CustomCellName*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

编辑:而不是使用 tag使用单元格的按钮操作,您可以像这样尝试。
-(void)oneYearButtonAction:(UIButton*)sender {
     CGPoint center= sender.center; 
     CGPoint rootViewPoint = [sender.superview convertPoint:center toView:self.tableView];
     NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
     CustomCellName *currentCell = [self.tableView cellForRowAtIndexPath:indexPath];
}

关于ios - CellForRowAtIndexPath 中给出的 UIButton 标记仅给出自定义 UITableViewCell 中的最后一个标记值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41821431/

相关文章:

iphone - 如何在表格 View 内显示表格单元格的详细 View ?

objective-c - 关于保留和复制

objective-c - 在 Objective-C 中,除了 DEBUG 之外还有 RELEASE 定义吗?

iOS。从位置创建到谷歌地图的网络链接

ios - 在 iOS 上的图像中查找非透明填充的 CGRect

iphone - float UITableViewCell

iphone - 如何更改单元格的 textLabel 框架?

android - Wowza 直播网址

objective-c - 快速找到数字的下一个倍数的方法

ios - 在 UIViewController 类中,@IBOutlet self.tableView 为 nil