ios - 选择单元格后 View 在不同单元格上重复

标签 ios objective-c uitableview

我有一个 tableviewcontroller 和一个自定义单元格。我想要做的是当我点击单元格时,单元格应该扩大并且 View (实际上是图形 View )应该在单元格内成为 subview 。现在的问题是一切正常,但图表也在其他一些单元格上重复。

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

    ProductsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (cell == nil)
    {
        NSLog(@"empty cell");
    }

    //Product Label
    cell.productNameLabel.text = @"something";

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    indexPathforChart = indexPath;
    [self performSelector:@selector(addChart:) withObject:indexPath afterDelay:0.2];
    [tableView beginUpdates];
    [tableView endUpdates];

    [tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];
}

-(void)addChart:(NSIndexPath*)indexPath
{   
        BEMSimpleLineGraphView *myGraph = [[BEMSimpleLineGraphView alloc] initWithFrame:CGRectMake(0, 60, screenSize.width, 200)];
        myGraph.dataSource = self;
        myGraph.delegate = self;
        myGraph.interpolateNullValues = YES;
        myGraph.enableTouchReport = YES;
        myGraph.tag = 100;
        myGraph.animationGraphStyle = BEMLineAnimationDraw;
        myGraph.enablePopUpReport = YES;
        myGraph.enableXAxisLabel = YES;
        myGraph.colorXaxisLabel = [UIColor darkGrayColor];

        ProductsTableViewCell *cell = (ProductsTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
        [cell.contentView addSubview:myGraph];
        [cell setNeedsLayout];
        [cell setNeedsDisplay];
        myGraph.colorTop = [UIColor clearColor];
        myGraph.colorBottom = [UIColor clearColor];
        myGraph.colorLine = [UIColor darkGrayColor];
        myGraph.colorPoint = [UIColor lightGrayColor];    
    }

最佳答案

这是由细胞重复使用引起的。

ProductsTableViewCell *cell = (ProductsTableViewCell*)[self.tableView
cellForRowAtIndexPath:indexPath];
[cell.contentView addSubview:myGraph];

当您滚动表格 View 时,当单元格被其他索引路径重新使用时,您将 myGraph 作为 subview 添加到单元格中而没有将其删除。

最合适的方法应该是在单元格内使用自定义 View 来绘制图形,而不是在需要时添加/删除图形 View 。为了滚动性能,您还可以缓存图形,以防用户来回滚动时使用它。

关于ios - 选择单元格后 View 在不同单元格上重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31824707/

相关文章:

ios - 带有自定义 URL 的 RKResponseDescriptor

ios - 从我的应用程序打开优步,在不使用 sdk 的情况下预先填充上车和下车位置

objective-c - 对于 NSProgress,完成处理程序是用于 UI 还是下载 Controller ?

ios - UITableViewCell 内部的 UISwitch

ios - 线程 1 : signal SIGABRT - multiple views

ios - 仅使用生产证书时无法注册推送通知

iphone - 我正在使用默认的 UITableViewCell 。我想从本地服务器在单元格上设置图像...cell.imageView.image

objective-c - NSS支持自动图形切换支持

ios - swift 3 : UITableViewCell disable selection style also disables selection

ios - 选择 Cell 时将 UITableViewCell 置于顶部