平移UITableViewCell时会显示什么视图?

时间:2013-02-20 20:57:26

标签: ios uitableview swipe gestures

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

我问的原因是因为我想改变这个“透露视图”的颜色。我想在刷新单元格时自定义每个tableViewCell下面的颜色。例如,如果您向左滑动第3行,则会在单元格后面看到蓝色。如果您向左滑动第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 个答案:

答案 0 :(得分:1)

啊哈!

我找到了一个优雅而精彩的解决方案。我快乐地摇晃着。

我在cell.contentView右侧添加了另一个视图,其中包含我想要的背景颜色。现在,当您滑动单元格时,右侧视图会随之拉动,因此它看起来就像是正在显示的视图。 (现在,如果你想把内容放在那里,这是另一个人的另一个复杂因素......我不是那样做的)我想做的就是让每个细胞能够有不同的显示颜色。好极了!注意,你必须使帧更长(即500),以便删除滑动看起来正确。

这是我的代码。

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