问题
Is there any way to make the top and bottom edges of an NSScrollView to fade to transparent? I've seen some code/answers that 'fades' it by adding a gradient of a certain color to the subview, basically, covering up the top and bottom with the background color. However, I would like it to actually fade to alpha=0, so you can actually see the contents of the view behind the scroll view. I'm planning my app to have various backgrounds behind this NSScrollView, and without any kind of transition on the borders it looks pretty cheap.
回答1:
Here is a ready-made bottom & top fade for you:
https://github.com/jnozzi/JLNFadingScrollView
You can configure its fade color (usually a gray/black for shadow or the scroll view’s background color for ‘fade-to-nothing’)
回答2:
Converted a simple iOS implementation from here to work with macOS Swift.
Put this in your NSScrollView
subclass:
let fadePercentage: Float = 0.05
override func layout() {
super.layout()
let transparent = NSColor.clear.cgColor
let opaque = NSColor.controlDarkShadowColor.cgColor
let maskLayer = CALayer()
maskLayer.frame = self.bounds
let gradientLayer = CAGradientLayer()
gradientLayer.frame = NSMakeRect(self.bounds.origin.x, 0, self.bounds.size.width, self.bounds.size.height)
gradientLayer.colors = [transparent, opaque, opaque, transparent]
gradientLayer.locations = [0, NSNumber(value: fadePercentage), NSNumber(value: 1 - fadePercentage), 1]
maskLayer.addSublayer(gradientLayer)
self.layer?.mask = maskLayer
}
来源:https://stackoverflow.com/questions/10488914/fade-out-top-and-bottom-of-an-nsscrollview