Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fade edges UIScrollView
#import <UIKit/UIKit.h>
@interface SNFadeScrollView : UIScrollView
@property (nonatomic) BOOL fadeTop;
@property (nonatomic) BOOL fadeBottom;
@end
#import <QuartzCore/QuartzCore.h>
#import "SNFadeScrollView.h"
@implementation SNFadeScrollView
- (id)initWithFrame:(CGRect)frame{
if(self = [super initWithFrame:frame]){
_fadeTop = YES;
_fadeBottom = YES;
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder{
if(self = [super initWithCoder:aDecoder]){
_fadeTop = YES;
_fadeBottom = YES;
}
return self;
}
- (void)setFadeTop:(BOOL)fadeTop{
if(_fadeTop != fadeTop){
_fadeTop = fadeTop;
[self layoutSubviews];
}
}
- (void)setFadeBottom:(BOOL)fadeBottom{
if(_fadeBottom != fadeBottom){
_fadeBottom = fadeBottom;
[self layoutSubviews];
}
}
- (void)layoutSubviews{
if(self.fadeTop || self.fadeBottom){
CGFloat fadeHeight = SCROLLVIEW_EDGE_FADE;
CALayer *maskLayer = [CALayer layer];
maskLayer.frame = self.bounds;
CALayer *solidLayer = [CALayer layer];
solidLayer.backgroundColor = [[UIColor blackColor] CGColor];
CGRect solidRect = CGRectZero;
solidRect.origin.x = self.contentOffset.x;
solidRect.size = self.bounds.size;
if(self.fadeTop){
solidRect.origin.y = fadeHeight;
}
if(self.fadeBottom){
solidRect.size.height -= solidRect.origin.y+fadeHeight;
}
solidLayer.frame = solidRect;
[maskLayer addSublayer:solidLayer];
if(self.fadeTop){
CAGradientLayer *topLayer = [CAGradientLayer layer];
topLayer.frame = CGRectMake(self.contentOffset.x, 0, self.bounds.size.width, fadeHeight);
topLayer.colors = @[(id)[[UIColor clearColor] CGColor], (id)[[UIColor blackColor] CGColor]];
topLayer.startPoint = CGPointZero;
topLayer.endPoint = CGPointMake(0, 1);
[maskLayer addSublayer:topLayer];
}
if(self.fadeBottom){
CAGradientLayer *bottomLayer = [CAGradientLayer layer];
bottomLayer.frame = CGRectMake(self.contentOffset.x, self.bounds.size.height-fadeHeight, self.bounds.size.width, fadeHeight);
bottomLayer.colors = @[(id)[[UIColor blackColor] CGColor], (id)[[UIColor clearColor] CGColor]];
bottomLayer.startPoint = CGPointZero;
bottomLayer.endPoint = CGPointMake(0, 1);
[maskLayer addSublayer:bottomLayer];
}
self.layer.mask = maskLayer;
}else{
self.layer.mask = nil;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.