我有两个 UIButton
在 UITableViewCell
子类,在 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/