NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to make a UIView fade out

Swift version: 5.2

Paul Hudson    @twostraws   

All views naturally fill the space assigned to them, but using CAGradientLayer as a mask view you can force a view to fade out at its edges.

To try it out, first create a test view with some obvious content like a background color:

let maskedView = UIView(frame: CGRect(x: 50, y: 50, width: 256, height: 256))
maskedView.backgroundColor = .blue

The next step is to create a CAGradientLayer at the same size as the view you want to mask:

let gradientMaskLayer = CAGradientLayer()
gradientMaskLayer.frame = maskedView.bounds

Now for the important part: to make the gradient work you need to use a clear color where nothing should be shown (where your view should be invisible) and white where the view should shine through fully.

By default GAGradientLayer spaces out its colors so they appear at equal distances, but we’re going to tell it to put the first color at 0, the second color at 0.1 (10% of the way in), the third color at 0.9 (90% of the way in), then the last color at 1 (the end). This 80% of our view is shown with full opacity:

gradientMaskLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor]
gradientMaskLayer.locations = [0, 0.1, 0.9, 1]

Finally, you just need to add that mask to your view, then add the whole thing to a parent view so it can be shown:

maskedView.layer.mask = gradientMaskLayer
view.addSubview(maskedView)
Hacking with Swift is sponsored by Instabug

SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.

Start your free trial!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Listen to the Swift over Coffee podcast

Available from iOS 3.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5