带有渐变颜色的滚动视图

Posted

技术标签:

【中文标题】带有渐变颜色的滚动视图【英文标题】:ScrollView with GradientColor 【发布时间】:2017-03-28 20:22:19 【问题描述】:

我正在尝试使用渐变背景颜色制作滚动视图,但它只显示渐变颜色并且看不到滚动视图!没有错误消失。

    mainScrollView.frame = view.frame
    imageArray = [#imageLiteral(resourceName: "business-improvement"), #imageLiteral(resourceName: "IMG_3601"), #imageLiteral(resourceName: "IMG_4261"), #imageLiteral(resourceName: "IMG_4264")]


    for i in 0..<imageArray.count

        let imageView = UIImageView()
        imageView.image = imageArray[i]
        imageView.contentMode = .scaleAspectFit
        let xPosition = self.view.frame.width * CGFloat(i)
        imageView.frame = CGRect(x: xPosition, y:0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)

        let mainScrollView = CAGradientLayer()
        self.view.backgroundColor = UIColor(red: 0.01, green:0.34, blue: 0.38, alpha: 1.0)
        mainScrollView.frame = self.view.bounds
        let color1 = UIColor(red: 0.11, green:0.04, blue: 0.32, alpha: 1.0).cgColor
        let color2 = UIColor(red: 0.0, green:0.18, blue: 0.20, alpha: 1.0).cgColor
        mainScrollView.colors = [color1, color2]
        mainScrollView.frame = CGRect(x: 0, y: 0, width: 375, height: 690)
        self.view.layer.addSublayer(mainScrollView)

【问题讨论】:

【参考方案1】:

我也尝试过,这对我有用:

 self.MyItem.applyGradient_2(colours: [UIColor(red:0.09, green:0.91, blue:0.65, alpha:1.0), UIColor(red:0.08, green:0.92, blue:0.43, alpha:1.0)])

extension UIView 
    func applyGradient_2(colours: [UIColor]) -> Void 
        self.applyGradient_(colours: colours, locations: nil)
    

    func applyGradient_(colours: [UIColor], locations: [NSNumber]?) -> Void 
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map  $0.cgColor 
        gradient.locations = locations
        self.layer.insertSublayer(gradient, at: 0)
    

【讨论】:

以上是关于带有渐变颜色的滚动视图的主要内容,如果未能解决你的问题,请参考以下文章

滚动视图时黑色到清晰渐变消失

带有渐变的SwiftUI ScrollView文本

当有其他内容时,滚动视图顶部/底部的渐变

带有 uiscrollview 分页的 iOS 渐变动画

iOS7,渐变作为背景在表格视图中滚动

如何在 iOS swift 运行时更新 CAGradientLayer 颜色?