UIView transparent gradient UIView transparent gradient ios ios

UIView transparent gradient


This was an embarrassingly easy fix: apply a CAGradientLayer as my subview's mask.

CAGradientLayer *gradientLayer = [CAGradientLayer layer];gradientLayer.frame = _fileTypeScrollView.bounds;gradientLayer.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor, nil];gradientLayer.startPoint = CGPointMake(0.8f, 1.0f);gradientLayer.endPoint = CGPointMake(1.0f, 1.0f);_fileTypeScrollView.layer.mask = gradientLayer;

Thanks to Cocoanetics for pointing me in the right direction!


This is how I'll do.

Step 1 Define a custom gradient view (Swift 4):

import UIKitclass GradientView: UIView {    override open class var layerClass: AnyClass {        return CAGradientLayer.classForCoder()    }    required init?(coder aDecoder: NSCoder) {        super.init(coder: aDecoder)        let gradientLayer = self.layer as! CAGradientLayer        gradientLayer.colors = [            UIColor.white.cgColor,            UIColor.init(white: 1, alpha: 0).cgColor        ]        backgroundColor = UIColor.clear    }}

Step 2 - Drag and drop a UIView in your storyboard and set its custom class to GradientView

enter image description here

As an example, this is how the above gradient view looks like:


https://github.com/yzhong52/GradientViewDemo


Gradient Example

I just ran into the same issue and wound up writing my own class. It seems like serious overkill, but it was the only way I could find to do gradients with transparency. You can see my writeup and code example here

It basically comes down to a custom UIView that creates two images. One is a solid color, the other is a gradient that is used as an image mask. From there I applied the resulting image to the uiview.layer.content.

I hope it helps,Joe