【问题标题】:Change Gradient Background of UIView Through Sublayer通过 Sublayer 改变 UIView 的渐变背景
【发布时间】:2020-08-27 05:51:21
【问题描述】:

我在UIView 的扩展中定义了这个函数,我用它在UIView 上设置渐变背景:

func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius : CGFloat){
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
    gradientLayer.locations = [0, 1]
    gradientLayer.frame = bounds
    gradientLayer.cornerRadius = withCornerRadius
    layer.insertSublayer(gradientLayer, at: 0)
}

用法如下:

view.setGradientBackground(colorTop: UIColor.blue, colorBottom: UIColor.red, withCornerRadius: 10)

问题是,如果我已经在一个视图上调用了这个函数一次,那么我第二次调用它时,它什么也不做。我怀疑这是由先前插入的subLayer 引起的。

我已经尝试添加:

if layer.sublayers?.count ?? 0 > 0 {
    layer.sublayers?.remove(at: 0)
}

到该函数的顶部,但这会导致代码崩溃并出现BAD_INSTRUCTION 异常。

【问题讨论】:

    标签: ios swift extension-methods cagradientlayer


    【解决方案1】:

    你可以获得渐变层,并且可以从任何你想从视图中删除......不仅仅是通过再次添加它你删除它..

    if let gradientLayer = (yourView.layer.sublayers?.compactMap { $0 as? CAGradientLayer })?.first {
    
        print("gradientLayer is presnet")
           gradientLayer.removeFromSuperlayer() 
    
    } else {
    
        print("its not added on layer yet")
    }
    

    【讨论】:

      【解决方案2】:

      最简单的选择是检查图层的子图层是否为渐变图层。这并不完全安全,因为如果您碰巧在子层的索引 0 处有另一个渐变层,它将更改不正确的子层。

      func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius cornerRadius: CGFloat) {
        let gradientLayer = layer.sublayers?.first as? CAGradientLayer ?? CAGradientLayer()
        // The rest of your existing layer customization code here
      
        guard gradientLayer.superlayer != self else {
          return
        }
        layer.sublayers?.insertSublayer(gradientLayer, at: 0)
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 2015-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多