Skip to content

Instantly share code, notes, and snippets.

@TucoBZ
Forked from lpbas/FadeView.swift
Created June 9, 2023 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TucoBZ/3ec201db8a87c187efb273019a6f1cd6 to your computer and use it in GitHub Desktop.
Save TucoBZ/3ec201db8a87c187efb273019a6f1cd6 to your computer and use it in GitHub Desktop.
Fade a UIView in iOS using Gradient (Swift Extension)
//
// This program is free software. It comes without any warranty, to
// the extent permitted by applicable law. You can redistribute it
// and/or modify it under the terms of the Do What The Fuck You Want
// To Public License, Version 2, as published by Sam Hocevar. See
//
// http://sam.zoy.org/wtfpl/COPYING
//
// for more details.
//
///
/// With this extension you can call .fadeView(style: ) on any view to create a fading effect.
/// Very useful when trying to fade a UIScrollView, UITableView or UICollectionView
/// This way also takes care of the "white or black" transparent gradient that happens as described here: https://stackoverflow.com/questions/24882361/ios-white-to-transparent-gradient-layer-is-gray
/// This solution is a swift implementation of the following stackoverflow question in Swift, adding more styles: https://stackoverflow.com/questions/17774761/how-to-create-a-top-fade-effect-using-uiscrollview/25408833#25408833
///
extension UIView {
enum UIViewFadeStyle {
case bottom
case top
case left
case right
case vertical
case horizontal
}
func fadeView(style: UIViewFadeStyle = .bottom, percentage: Double = 0.07) {
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = [UIColor.white.cgColor, UIColor.clear.cgColor]
let startLocation = percentage
let endLocation = 1 - percentage
switch style {
case .bottom:
gradient.startPoint = CGPoint(x: 0.5, y: endLocation)
gradient.endPoint = CGPoint(x: 0.5, y: 1)
case .top:
gradient.startPoint = CGPoint(x: 0.5, y: startLocation)
gradient.endPoint = CGPoint(x: 0.5, y: 0.0)
case .vertical:
gradient.startPoint = CGPoint(x: 0.5, y: 0.0)
gradient.endPoint = CGPoint(x: 0.5, y: 1.0)
gradient.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor]
gradient.locations = [0.0, startLocation, endLocation, 1.0] as [NSNumber]
case .left:
gradient.startPoint = CGPoint(x: startLocation, y: 0.5)
gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
case .right:
gradient.startPoint = CGPoint(x: endLocation, y: 0.5)
gradient.endPoint = CGPoint(x: 1, y: 0.5)
case .horizontal:
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor]
gradient.locations = [0.0, startLocation, endLocation, 1.0] as [NSNumber]
}
layer.mask = gradient
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment