Skip to content

Instantly share code, notes, and snippets.

@ppth0608
Last active July 2, 2019 15:59
Show Gist options
  • Save ppth0608/ac5fad6ff98882a328220209b293b329 to your computer and use it in GitHub Desktop.
Save ppth0608/ac5fad6ff98882a328220209b293b329 to your computer and use it in GitHub Desktop.
Add Gradient Layer(.clear to .black) on UIView
import UIKit
protocol GradientEffect {
var gradientEffectEnabled: Bool { get set }
}
extension GradientEffect where Self: UIView {
func setGradientView() {
let gradientView = UIView(frame: bounds)
let gradient = CAGradientLayer()
gradient.frame = gradientView.bounds
gradient.colors = [UIColor.clear.cgColor, UIColor.black.withAlphaComponent(0.3).cgColor]
gradient.locations = [0.0, 1.0]
gradientView.layer.insertSublayer(gradient, at: 0)
addSubview(gradientView)
bringSubviewToFront(gradientView)
}
}
extension UIView: GradientEffect {
private struct LayerKey {
static let gradientEffectEnabled = "gradientEffectEnabled"
}
@IBInspectable var gradientEffectEnabled: Bool {
get {
return layer.value(forKey: LayerKey.gradientEffectEnabled) as? Bool ?? false
} set {
layer.setValue(newValue, forKey: LayerKey.gradientEffectEnabled)
if newValue {
setGradientView()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment