对 UICollectionView 的顶部和底部应用淡入淡出效果

Apply fade effect to top and bottom of UICollectionView

我已经阅读了这里的示例,但我无法按照我想要的方式进行,不知何故我的渐变示例卡在屏幕中间,没有按预期工作。

我有一个 UICollectionView 用垂直滚动填充整个屏幕。

我希望 UICollectionView 的顶部和底部为黑色,中间为透明(因为我使用的是黑色 blackgroundColor)。

我尝试应用渐变,但不知何故未能完成我想要的。

这是我的代码:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.black.cgColor, UIColor.clear.cgColor, UIColor.black.cgColor]
gradient.startPoint = CGPoint(x: 1, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
view.layer.mask = gradient

上面的代码将渐变放置在屏幕中间但倒置了。渐变全黑时,屏幕顶部和底部以及中间部分是透明的。

我正在尝试创建这样的东西:

感谢您的帮助

您可以通过以下方式更改颜色线来实现:

gradient.colors = [
    UIColor(white: 1.0, alpha: 0).cgColor,
    UIColor(white: 1.0, alpha: 1).cgColor,
    UIColor(white: 1.0, alpha: 0).cgColor
]

或者,如果您想更好地控制渐变,您还可以使用下面的代码并调整位置 and/or 颜色 alpha 值:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [
    UIColor(white: 1, alpha: 0).cgColor,
    UIColor(white: 1, alpha: 1).cgColor,
    UIColor(white: 1, alpha: 1).cgColor,
    UIColor(white: 1, alpha: 0).cgColor
]
gradient.locations = [0, 0.4, 0.6, 1]
view.layer.mask = gradient

文档中的原因;

An optional layer whose alpha channel is used to mask the layer’s content.

The layer’s alpha channel determines how much of the layer’s content and background shows through. Fully or partially opaque pixels allow the underlying content to show through but fully transparent pixels block that content.