Search code examples
iosuiscrollviewtableviewcustom-cell

Do not add an existing item in the cellForRowAtIndexPath


In my TableViewController I use custom cell, this cell has a scrollView. My cellForRowAtIndexPath method looks like:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (!cell) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];

        // iOS 7 separator
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            cell.separatorInset = UIEdgeInsetsZero;
        }

    }

    UIView *subview = [cell viewWithTag:indexPath.row + 1];
    if (!subview) {
       //... Set up the new cell
        [self addScrollViewForCell:cell andCellIndx:indexPath.row];
    }
    else {
       // ... Reuse the cell
    }

    return cell;
}

If view already exist - I'm trying do not add scrollView. If not - add. addScrollViewForCell: method:

- (void)addScrollViewForCell: (CustomCell *)tCell andCellIndx:(NSInteger)cIndx {

    UIScrollView * myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(5, 62, 350, 61)];
    myScrollView.accessibilityActivationPoint = CGPointMake(100, 100);

    //Some settings
    // ...

    UILabel *lblH = [[UILabel alloc] init];
    lblH.textAlignment = NSTextAlignmentCenter;
    lblH.text = strWeekIdntfr;
    lblH.textColor = [UIColor blueColor];
    lblH.frame = CGRectMake(offsetScores, 0, cCurrWeekBallsWidth, 15);

    [myScrollView addSubview:lblH];

     myScrollView.tag = cIndx + 1;
     [tCell addSubview:myScrollView];
}

The problem is - when I scroll table to the bottom or to the up, scrollView begin to be added. Checking view by tag I try to differentiate reusable and new one cells, but this didn't work. How Can I solve this?


Solution

  • The best way that I found it just clear all subview from scrollView. For example like that:

    [myCell.scrollView.subviewsmakeObjectsPerformSelector:@selector(removeFromSuperview)];