iOS 仿花椒直播聊天室消息列表渐隐消失效果

最近,项目需要做一个类似花椒直播,消息列表渐隐消失的效果。先上图:


iOS 仿花椒直播聊天室消息列表渐隐消失效果_第1张图片
效果静态图.png
动态图.gif

从效果上分析:在消息列表加了一个蒙层(遮罩),蒙层的颜色为透明颜色,在消息列表顶部设置颜色渐变,从而达到顶部的消息一个渐隐的效果。


所需要用的类
  • UITableView :消息列表
  • CAGradientLayer :颜色渐变蒙层

在初始化 TableView 的时候,给 Tableview 添加一个CAGradientLayer蒙层

- (UITableView *)tableView {
    
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, [UIScreen mainScreen].bounds.size.width, 400) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 200;
        
        // 渐变蒙层
        CAGradientLayer *layer = [[CAGradientLayer alloc] init];
        layer.colors = @[
                         (__bridge id)[UIColor colorWithWhite:0 alpha:0.05f].CGColor,
                         (__bridge id)[UIColor colorWithWhite:0 alpha:1.0f].CGColor
                         ];
        layer.locations = @[@0, @0.4]; // 设置颜色的范围
        layer.startPoint = CGPointMake(0, 0); // 设置颜色渐变的起点
        layer.endPoint = CGPointMake(0, 1); // 设置颜色渐变的终点,与 startPoint 形成一个颜色渐变方向
        layer.frame = _tableView.bounds; // 设置 Frame
        
        _tableView.layer.mask = layer; // 设置 mask 属性
    }
    
    return _tableView;
}

效果图:

效果图

没有滑动tableViewtableView顶部到底部有一个从模糊到清晰的效果,但是滑动之后,发现tableView的顶部不再模糊,我的想法是因为scrollView的特性,导致蒙层已经随着滚动上去了,所以我的解决方案是在ScrollView的代理方法中,再次设置蒙层。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CAGradientLayer *layer = [[CAGradientLayer alloc] init];
    layer.colors = @[
                     (__bridge id)[UIColor colorWithWhite:0 alpha:0.05f].CGColor,
                     (__bridge id)[UIColor colorWithWhite:0 alpha:1.0f].CGColor
                     ];
    layer.locations = @[@0, @0.4];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1);
    layer.frame = _tableView.bounds;
    
    _tableView.layer.mask = layer;
}

最终效果图:

最终效果图

不知道是否还有更好的方案,在此提出来,希望能跟更多人交流。

你可能感兴趣的:(iOS 仿花椒直播聊天室消息列表渐隐消失效果)