正确的方法将标签设置为TableView中的所有单元格

CGR*_*CGR 2 objective-c uitableview ios

我正在使用一个按钮tableView,我indexPath.row按下按钮.但是只有当细胞可以在屏幕上显示时才能正常工作scroll.

一旦tableView可以滚动并且我滚动到tableview,indexPath.row返回的是一个错误的值,我注意到最初设置20个对象,例如Check只打印9次没有20.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil) {
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

       lBtnWithAction = [[UIButton alloc] initWithFrame:CGRectMake(liLight1Xcord + 23, 10, liLight1Width + 5, liLight1Height + 25)];
       lBtnWithAction.tag = ROW_BUTTON_ACTION;
       lBtnWithAction.titleLabel.font = luiFontCheckmark;
       lBtnWithAction.tintColor = [UIColor blackColor];
       lBtnWithAction.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
       [cell.contentView addSubview:lBtnWithAction];
   }
   else 
   { 
       lBtnWithAction = (UIButton *)[cell.contentView viewWithTag:ROW_BUTTON_ACTION];
   }

//Set the tag
lBtnWithAction.tag = indexPath.row;
//Add the click event to the button inside a row
[lBtnWithAction addTarget:self action:@selector(rowButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

//This is printed just 9 times (the the number of cells that are initially displayed in the screen with no scroll), when scrolling the other ones are printed
NSLog(@"Check: %li", (long)indexPath.row);

return cell;
}
Run Code Online (Sandbox Code Playgroud)

要对点击的索引执行某些操作:

-(void)rowButtonClicked:(UIButton*)sender
{
    NSLog(@"Pressed: %li", (long)sender.tag);
}
Run Code Online (Sandbox Code Playgroud)

Constants.h

#define ROW_BUTTON_ACTION 9
Run Code Online (Sandbox Code Playgroud)

当我有很多单元格时,获取indexPath.row内部rowButtonClicked或设置标签的正确方法是什么tableView

mat*_*att 7

我对这类问题的解决方案是不要以这种方式使用标签.这是对标签的完全滥用(在我看来),并且很可能会引起麻烦(正如您所发现的那样),因为细胞会被重复使用.

通常,要解决的问题是:单元格中的一个界面与用户进行交互(例如,点击一个按钮),现在我们想知道该单元格当前对应的,以便我们可以尊重到相应的数据模型.

我在我的应用程序中解决这个问题的方法是,当点击按钮或其他任何东西并且我从它接收控制事件或委托事件时,从界面的那一部分(按钮或其他)走向视图层次结构直到我来到单元格,然后调用表视图indexPath(for:),它取一个单元格并返回相应的索引路径.控制事件或委托事件始终将接口对象作为参数包含在内,因此很容易从该对象到单元格以及从那里到行.

因此,例如:

UIView* v = // sender, the interface object
do {
    v = v.superview;
} while (![v isKindOfClass: [UITableViewCell class]]);
UITableViewCell* cell = (UITableViewCell*)v;
NSIndexPath* ip = [self.tableView indexPathForCell:cell];
// and now we know the row (ip.row)
Run Code Online (Sandbox Code Playgroud)

[ 注意可能的替代方法是使用自定义单元子类,在该子类中有一个特殊属性,用于存储行cellForRowAt.但这在我看来完全没有必要,因为看到它indexPath(for:)给你完全相同的信息!在另一方面,不存在indexPath(for:)对于一个页眉/页脚,所以在这种情况下,我使用存储所述节号,如在自定义子类此示例中(参见实施viewForHeaderInSection).]