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:
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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…