Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 为包含CAGradientLayer的UIView设置动画_Swift_Animation_Gradient - Fatal编程技术网

Swift 为包含CAGradientLayer的UIView设置动画

Swift 为包含CAGradientLayer的UIView设置动画,swift,animation,gradient,Swift,Animation,Gradient,我想修改具有渐变层的视图的宽度,但当我添加渐变层时,这会阻止动画 我向您展示我的代码: override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() animateProgressBar(leftPourcentage : 64) addGradientBarColor() } func addGradientBarColor(leftPourcentage : CGFloat){ l

我想修改具有渐变层的视图的宽度,但当我添加渐变层时,这会阻止动画

我向您展示我的代码:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    animateProgressBar(leftPourcentage : 64)
    addGradientBarColor()
}

func addGradientBarColor(leftPourcentage : CGFloat){
    let leftColor = UIColor(rgb: 0x00ABBD)
    let rightColor = UIColor(rgb : 0x00DAFF)
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [leftColor.cgColor,
                            rightColor.cgColor]

    gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
    gradientLayer.frame = CGRect.init(
        x: userBarLeft.bounds.origin.x,
        y: userBarLeft.bounds.origin.y,
        width: userBarLeft.frame.width,
        height: userBarLeft.frame.height)
    gradientLayer.masksToBounds = false
    gradientLayer.cornerRadius = 2
    userBarLeft.layer.insertSublayer(gradientLayer, at: 0)
}

func animateProgressBar(leftPourcentage : CGFloat){
    let widthOfTotalBarLeft = totalBarLeft.bounds.size.width

    leftBarWidthConstr.constant = widthOfTotalBarLeft * (leftPourcentage / 100)
    UIView.animate(withDuration: 2) {
        self.view.layoutIfNeeded()
    } 
}
这让我看到:

没有动画作品

当我删除
addGradientBarColor
功能时,会显示:


我想动画,但梯度。如何实现这一点?

这是因为您将渐变宽度设置为

width: userBarLeft.frame.width,
那就去吧

width:0,

感谢您的回复,当我在
动画部分添加这个
self.gradientLeftLayer.bounds.size.width=widthofttotalbarleft*(leftPourcentage/100)
时,这不起作用。如何设置
CAGradientLayer
宽度的动画?将渐变嵌入视图并设置其完整框架的动画无法使用视图动画(
UIView.animate
)设置层布局的动画。使用渐变视图而不是渐变层。例如,见