最近,項目需要做一個類似花椒直播,消息列表漸隱消失的效果。先上圖:
效果靜態圖.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;
}
效果圖:
效果圖
沒有滑動tableView
,tableView
頂部到底部有一個從模糊到清晰的效果,但是滑動之后,發現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;
}
最終效果圖:
最終效果圖
不知道是否還有更好的方案,在此提出來,希望能跟更多人交流。