到达底部时,移除底部的ScrollView渐变淡入度

时间:2019-01-07 11:56:39

标签: ios swift uiscrollview cagradientlayer

我有一个UIScrollView,它具有一个淡出的底部渐变层(如下面的screeshot中所示)。我想在到达UIScrollView底部时将其删除。我发现以下帖子,但对我没有任何帮助。

https://stablekernel.com/how-to-fade-out-content-using-gradients-in-ios/

Fade edges of UITableView

let gradient = CAGradientLayer()
gradient.frame = myTextView.bounds
gradient.colors = [UIColor.clear.cgColor, UIColor.black.cgColor, UIColor.black.cgColor, UIColor.clear.cgColor]
gradient.locations = [0, 0.0, 0.7, 1]
myTextView.layer.mask = gradient

override func layoutSubviews() {
    gradient.frame = kvkkTextView.bounds
}

当我尝试更改

中的渐变框架时
private func updateGradientFrame() {
gradient.frame = CGRect(
    x: 0,
    y: kvkkTextView.contentOffset.y,
    width: kvkkTextView.bounds.width,
    height: kvkkTextView.bounds.height
)
}

它会导致一个奇怪的错误。滚动时,屏幕上的文字会慢慢显示(快速滚动时,屏幕上的文字会变成空白,然后出现文本)。

screenshot

1 个答案:

答案 0 :(得分:1)

尝试一下

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    updateGradientFrame()

    //On the scroll view content is over means there is no content anymore then hide the mask
    if scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.bounds.height {

        label.layer.mask = nil
    } else {

        //Else show the mask of UILabel
        label.layer.mask = gradient
    }
}

更新:

private func updateGradientFrame() {
    gradient.frame = CGRect(
        x: 0,
        y: scrollView.contentOffset.y,
        width: scrollView.bounds.width,
        height: scrollView.bounds.height
        )
}

GitHub网址:https://github.com/sateeshyegireddi/GradientScrollViewDemo