UITableViewCell点击效果解决方案

6,614 阅读1分钟

开启点击效果

  • 方案1:设置cell的selectedBackgroundView属性,并设置相应的颜色值
    self.selectedBackgroundView = [[UIView alloc]initWithFrame:self.bounds];
    self.selectedBackgroundView.backgroundColor = kSelectTapEffectColor;
  • 方案2:取消cell选中状态样式,重写以下两个方法
self.selectionStyle = UITableViewCellSelectionStyleNone;
// 配置cell高亮状态
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [super setHighlighted:highlighted animated:animated];
    if (highlighted) {
        self.contentView.backgroundColor = kSelectTapEffectColor;
    } else {
        // 增加延迟消失动画效果,提升用户体验
        [UIView animateWithDuration:0.1 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.contentView.backgroundColor = [UIColor whiteColor];
        } completion:nil];
    }
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    if (selected) {
        self.contentView.backgroundColor = kSelectTapEffectColor;
    } else {
        self.contentView.backgroundColor = [UIColor whiteColor];
    }
}

方案对比:

  • 方案1: 方便快捷,但会选中时会使子视图的背景色变透明,影响原有的视觉效果,在视图元素背景较为单一时推荐使用
  • 方案2:代码量稍多,但弥补了方案1的缺点,不会改变原有的视觉效果。

关闭点击效果

self.selectionStyle = UITableViewCellSelectionStyleNone;