Правильный способ установки тега для всех ячеек в TableView
Я использую кнопку внутриtableView
в котором я получаюindexPath.row
когда нажата. Но это работает только тогда, когда клетки могут быть отображены на экране безscroll
.
После того, как 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;
}
Чтобы сделать что-то с индексом, на который нажали:
-(void)rowButtonClicked:(UIButton*)sender
{
NSLog(@"Pressed: %li", (long)sender.tag);
}
Constants.h
#define ROW_BUTTON_ACTION 9
Как правильно получитьindexPath.row
внутриrowButtonClicked
или установить тег, когда у меня много ячеек в моемtableView
?