Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...