首页 > 解决方案 > 为什么 UIView.animate 在 vi​​ew.layer 和 sublayer 上执行不同的结果

问题描述

这是我的代码:

        let colorLayer = CALayer()
        colorLayer.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        colorLayer.backgroundColor = UIColor.blue.cgColor

        let blockView = UIView.init(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        blockView.backgroundColor = UIColor.red
        self.view.addSubview(blockView)

        blockView.layer.addSublayer(colorLayer)

        Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { (t) in
            UIView.animate(withDuration: 1.0) { [self] in
                // this animation lasts 1s
//                let transform = blockView.layer.affineTransform()
//                blockView.layer.setAffineTransform(transform.rotated(by: CGFloat(Double.pi / 2.0)))
                // while this animation 0.25s
                let transform2 = colorLayer.affineTransform()
                colorLayer.setAffineTransform(transform2.rotated(by: CGFloat(Double.pi / 2.0)))
            } completion: { (complete) in

            }

        })

为什么我的自定义子图层colorLayer旋转 0.25 秒(默认值),而不是由withDuration:参数设置,但blockView.layer工作正常?

标签: iosswiftuiviewcore-animationcalayer

解决方案


UIView 动画旨在对 UIView 对象的可动画属性的更改进行动画处理。它们不是用来为 CALayer 属性设置动画的。

UIView 动画调用可能根本没有为您更改 colorLayer 的代码设置动画。只是 CALayer 的 transform 属性支持隐式动画,因此更改它会触发隐式动画。我希望该行在 UIView 动画之外具有完全相同的效果。

我怀疑您对块视图应用仿射变换的调用是有效的,因为它结束了更改您将通过使用类似代码更改的相同变换属性

blockView.transform = blockView.transform.rotated(by: CGFloat(Double.pi / 2.0)

简短的回答:不要尝试使用 UIView 动画为图层属性设置动画。它通常不起作用。


推荐阅读