Search code examples
swiftuitableviewnsarraylinear-gradients

Apply vertical alpha gradient to UITableView


I'm new to iOS development and am trying to learn Swift. I'd like to apply a vertical alpha gradient to a UITableView, but am having some trouble.

Originally following this SO post, I did the following:

var gradientMaskLayer:CAGradientLayer = CAGradientLayer()
gradientMaskLayer.frame = myTableView.bounds
gradientMaskLayer.colors = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor]
gradientMaskLayer.locations = [0.0, 0.05]
myTableView.layer.mask = gradientMaskLayer

After getting the error Array element cannot be bridged to Objective-C and reading this SO post I modified the two arrays used:

var gradientMaskLayer:CAGradientLayer = CAGradientLayer()
var gradientMaskColors:NSArray = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor]
var gradientMaskLocations:NSArray = [0.0, 0.05]
gradientMaskLayer.frame = myTableView.bounds
gradientMaskLayer.colors = gradientMaskColors
gradientMaskLayer.locations = gradientMaskLocations
myTableView.layer.mask = gradientMaskLayer

And now get the error Value failed to bridge from Swift type to a Objective-C type

I'm struggling to find a solution. Can any lend some assistance?


Solution

  • You should mask the superview, not the view itself.

    Here's an example:

    let gradient = CAGradientLayer()
    
    gradient.frame = tableView.superview?.bounds ?? .null
    gradient.colors = [UIColor.clear.cgColor, UIColor.clear.cgColor, UIColor.black.cgColor, UIColor.black.cgColor, UIColor.clear.cgColor, UIColor.clear.cgColor]
    gradient.locations = [0.0, 0.15, 0.25, 0.75, 0.85, 1.0]
    tableView.superview?.layer.mask = gradient
    
    tableView.backgroundColor = .clear
    

    Result:

    Mask + TableView

    You can change the orientation by changing the startPoint and endpoint properties. The default values (vertically) are (0.5, 0.0) and (0.5, 1) respectively. Point (0,0) is the bottom-left corner of the layer and (1,1) is the top-right corner. For example, if you want to apply that mask horizontally instead of vertically, just do:

    gradient.startPoint = .init(x: 0.0, y: 0.5)
    gradient.endPoint = .init(x: 1.0, y: 0.5)
    

    One more thing: if you're using AutoLayout, then you need to update the layer with the correct CGRect value. I usually override layoutSubviews() method to update it like gradient.frame = tableView.superview?.bounds ?? .null.