代码之家  ›  专栏  ›  技术社区  ›  Ed Chin

平移UITableViewCell时显示的视图是什么?

  •  0
  • Ed Chin  · 技术社区  · 12 年前

    我正在平移UITableViewCell内容视图,如下代码所示。我想知道正在移动的UITableViewCell内容视图后面的视图是什么?

    我之所以这么问,是因为我想改变这种“揭示的观点”的颜色。我想在滑动单元格时自定义每个表ViewCell下面的颜色。例如,如果向左滑动第三行,则会在单元格后面看到蓝色。如果你向左滑动第4行,你会看到单元格后面的绿色。

    - (void)panGestureRecognizer:(UIPanGestureRecognizer *)recognizer {
    
        //...
    
        if ((recognizer.state == UIGestureRecognizerStateBegan
             || recognizer.state == UIGestureRecognizerStateChanged)
            && [recognizer numberOfTouches] > 0) {
    
            CGPoint location1 = [recognizer locationOfTouch:0 inView:self.tableView];
            NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location1];           
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
            CGPoint translation = [recognizer translationInView:self.tableView];
            cell.contentView.frame = CGRectOffset(cell.contentView.bounds, translation.x, 0);
        }
    
        //...
    }
    

    我尝试过的一件事是创建一个UIView,并将其添加到contentView后面的单元格中。这是有效的,但我并不满意。如果使用UITableViewRowAnimationLeft输入代码以设置删除单元格的动画,则背景颜色将随单元格向左移动。这是有道理的,因为当动画将单元格移出以删除它时,我创建的背景视图会随着整个单元格一起移动。我想要的行为是背景颜色实际位于单元格后面,因此在删除动画中移动单元格时不会移动。

    下面的代码是如何将背景视图添加到单元格中并将其放在contentView下面的。

    [cell.contentView setBackgroundColor:[UIColor whiteColor]];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, self.tableView.rowHeight)];
    view.backgroundColor = [UIColor redColor];
    [cell addSubview:view];  
    [cell bringSubviewToFront:cell.contentView];
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   Ed Chin    12 年前

    啊哈!

    我找到了一个优雅而美妙的解决方案。我高兴得手足无措。

    我在单元格右侧添加了另一个视图。使用我想要的背景色查看。现在,当你滑动单元格时,右侧视图会随之移动,看起来就像是要显示的视图。(现在,如果你想把内容放在那里,那对另一个人来说是另一个复杂的问题……我不会这么做)我只想让每个细胞都能有不同的显示颜色。耶!请注意,您必须使框架超长(即500),以便滑动删除看起来正确。

    这是我的密码。

    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(320, 0, 500, self.tableView.rowHeight)];
    label.backgroundColor = [UIColor redColor];
    [cell.contentView addSubview:label];