动态 backgroundColor UIImageView 不更新 iOS

Dynamic backgroundColor UIImageView does not update iOS

当我移动第一个 UIImageView 的视图光标时,我使用 UIPanGestureRecognizer 输出点 rgb 的颜色。使用这种颜色,我必须在第二个 uiview 中创建一个渐变,该渐变从起始颜色的左侧开始,到白色的右侧。我注意到在计算第一个 rgb 后,第二个 UIView 的 backgroundColor 的颜色得到了纠正,但是在移动了第一个 UIView 的光标并更改了 rgb 颜色之后,第二个 uiview 的 backgroundColor 保持不变。

  @objc func wasDragged(gestureRecognizer: UIPanGestureRecognizer) {

    if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {

        let translation = gestureRecognizer.translation(in: self.view)

        gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
        gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
        let color = self.imageView.getPixelColorAt(point: gestureRecognizer.view!.center)
       // color is correct

        UIView.animate(withDuration: 1, delay: 0.0, options:[.repeat, .autoreverse], animations: {
             self.gradientview.backgroundColor = UIColor.clear
             self.gradientview.gradientBackground(from: color, to:   UIColor.white, direction: GradientDirection.leftToRight)
       // color is correct only first time, after remains unchanged
        }, completion:nil)

    }
 }

在扩展中

我从这个例子开始创建渐变 Programmatically create a UIView with color gradient

  enum GradientDirection {
     case leftToRight
     case rightToLeft
    case topToBottom
    case bottomToTop
 }

 extension UIView {
     func gradientBackground(from color1: UIColor, to color2: UIColor, direction: GradientDirection) {
    let gradient = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = [color1.cgColor, color2.cgColor]

    switch direction {
    case .leftToRight:
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    case .rightToLeft:
        gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
    case .bottomToTop:
        gradient.startPoint = CGPoint(x: 0.5, y: 1.0)
        gradient.endPoint = CGPoint(x: 0.5, y: 0.0)
    default:
        break
    }

    self.layer.insertSublayer(gradient, at: 0)
 }
}

你必须设置为nil all sublayer

 self.gradientview.backgroundColor = UIColor.clear
 self.gradientview.layer.sublayers = nil

 UIView.animate(withDuration: 1, delay: 0.0, options:[.repeat, .autoreverse], animations: {

            self.gradientview.gradientBackground(from: color, to: UIColor.white, direction: GradientDirection.leftToRight)


   }, completion:nil)