我拿了this的教程,做了一些修改和补充:
- 它现在适用于所有表格视图 - 即使它们是更大屏幕的一部分。
- 无论背景或 tableview 后面的任何内容如何,它都能正常工作。
- 遮罩的变化取决于表格视图的位置 - 滚动到顶部时只有底部褪色,滚动到底部时只有顶部褪色...
1.首先导入QuartzCore并在控制器中设置遮罩层:
编辑:不需要在课堂上引用CAGradientLayer。
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface mViewController : UIViewController
.
.
@end
2. 将此添加到 viewWillAppear viewDidLayoutSubviews:
(查看@Darren 对此的评论)
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
if (!self.tableView.layer.mask)
{
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.locations = @[[NSNumber numberWithFloat:0.0],
[NSNumber numberWithFloat:0.2],
[NSNumber numberWithFloat:0.8],
[NSNumber numberWithFloat:1.0]];
maskLayer.bounds = CGRectMake(0, 0,
self.tableView.frame.size.width,
self.tableView.frame.size.height);
maskLayer.anchorPoint = CGPointZero;
self.tableView.layer.mask = maskLayer;
}
[self scrollViewDidScroll:self.tableView];
}
3.通过将UIScrollViewDelegate 添加到控制器的.h 中,确保您是UIScrollViewDelegate 的代表:
@interface mViewController : UIViewController <UIScrollViewDelegate>
4.最后,在你的控制器.m中实现scrollViewDidScroll:
#pragma mark - Scroll View Delegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGColorRef outerColor = [UIColor colorWithWhite:1.0 alpha:0.0].CGColor;
CGColorRef innerColor = [UIColor colorWithWhite:1.0 alpha:1.0].CGColor;
NSArray *colors;
if (scrollView.contentOffset.y + scrollView.contentInset.top <= 0) {
//Top of scrollView
colors = @[(__bridge id)innerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)outerColor];
} else if (scrollView.contentOffset.y + scrollView.frame.size.height
>= scrollView.contentSize.height) {
//Bottom of tableView
colors = @[(__bridge id)outerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)innerColor];
} else {
//Middle
colors = @[(__bridge id)outerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)outerColor];
}
((CAGradientLayer *)scrollView.layer.mask).colors = colors;
[CATransaction begin];
[CATransaction setDisableActions:YES];
scrollView.layer.mask.position = CGPointMake(0, scrollView.contentOffset.y);
[CATransaction commit];
}
再次重申:大部分解决方案来自this cocoanetics 教程。