-
-
Save JesusMartinAlonso/bb35861558dea3d922daef1026cd01a7 to your computer and use it in GitHub Desktop.
Custom UIScrollView with fade effect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// FadeScrollView.swift | |
// | |
// Created by Jesus Martin Alonso on 24/06/2019. | |
// Inspired by https://gist.github.com/luismachado/1423427b4c60021d71a8772e4dabc140 | |
// Copyright © 2017 Luis Machado. All rights reserved. | |
import UIKit | |
/// UIScrollView subclass that fades the top/bottom edges depending of the scroll position | |
/// How to use it: | |
/// - Adds FadeScrollView to your view | |
/// - Set your view as UIScrollViewDelegate | |
/// - In scrollViewDidScroll delegate method call [updateGradient] | |
class FadeScrollView: UIScrollView { | |
let fadePoints: Float = 64.0 | |
let gradientLayer = CAGradientLayer() | |
let transparentColor = UIColor.clear.cgColor | |
let opaqueColor = UIColor.black.cgColor | |
var topFadingOpacity: CGColor { | |
let scrollOffset = contentOffset.y | |
let alpha:CGFloat = ( scrollOffset <= 0) ? 1 : 0 | |
let color = UIColor(white: 0, alpha: alpha) | |
return color.cgColor | |
} | |
var bottomFadingOpacity: CGColor { | |
let scrollViewHeight = frame.size.height | |
let scrollContentSizeHeight = contentSize.height | |
let scrollOffset = contentOffset.y | |
let alpha:CGFloat = (scrollOffset + scrollViewHeight >= scrollContentSizeHeight) ? 1 : 0 | |
let color = UIColor(white: 0, alpha: alpha) | |
return color.cgColor | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
let maskLayer = CALayer() | |
maskLayer.frame = self.bounds | |
let gradientLocation = fadePoints / Float(contentSize.height) | |
gradientLayer.frame = CGRect(x: self.bounds.origin.x, y: 0, width: self.bounds.size.width, height: self.bounds.size.height) | |
gradientLayer.colors = [topFadingOpacity, opaqueColor, opaqueColor, bottomFadingOpacity] | |
gradientLayer.locations = [0, NSNumber(value: gradientLocation), NSNumber(value: 1 - gradientLocation), 1] | |
maskLayer.addSublayer(gradientLayer) | |
self.layer.mask = maskLayer | |
} | |
/// Update gradient depending on content offset of the scrollview | |
/// Call this function in [scrollViewDidScroll] of UIScrollViewDelegate | |
func updateGradient() { | |
gradientLayer.colors = [topFadingOpacity, opaqueColor, opaqueColor, bottomFadingOpacity] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment