代码之家  ›  专栏  ›  技术社区  ›  willThatBeAll

如何在视图的直接层上启用动画?

  •  -1
  • willThatBeAll  · 技术社区  · 7 年前

    当我更改视图层的背景色时,它会立即更改,并且不会像子层那样设置动画。是什么禁用了此功能?

    class MyView: UIView {
    
        var mySublayer = CALayer()
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            layer.addSublayer(mySublayer)
            mySublayer.frame = bounds
        }
    }
    
    let view = MyView()
    
    view.layer.backgroundColor = UIColor.red.cgColor // this changes the background color instantly
    
    view.mySublayer.backgroundColor = UIColor.red.cgColor // this animates to the new color
    

    那么,是什么导致视图的直接层无法将其背景色设置为新颜色的动画呢?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sandeep Bhandari    7 年前

    可以使用动画块更改ViewController视图的背景色

        UIView.animate(withDuration: 10) {
            self.view.layer.backgroundColor = UIColor.green.cgColor
            //or you can use
            //self.view.backgroundColor = UIColor.green 
        }
    

    阅读 Animations 查找视图的可设置动画的属性。

    在iOS中,所有视图都是以图层为背景的,因此您可以随时更改图层的属性,这将影响与其关联的视图。

    编辑1:

    即使在提供了上面的答案之后,OP仍然看起来很困惑,所以添加一些信息以使其更容易理解。

    您的代码中似乎有几个问题。

    问题1:

    var mySublayer = CALayer()
    

    创建 CALayer 帧(0,0,0,0)的。你需要设置花环的框架。虽然我不明白你想对mySublayer做什么,但在它当前的状态下,它没有任何用处。设置背景色的动画 mySublayer 无论如何都不会帮助您,因为其帧为(0,0,0,0)

    你问,哪里是最好的放置框架的地方!您可以使用

    override func layoutSubviews() {
        super.layoutSubviews()
        self.someLayer.frame = self.frame
    }
    

    问题2:

    view.layer.backgroundColor = UIColor.red.cgColor
    

    上面的语句不会设置图层背景色属性值更改的动画。我已经在上面的答案中显示了,您必须使用 UIView.animate 要设置视图属性值更改的动画,您可以使用核心动画API,如 CABasicAnimation

    只需将值设置为视图的属性,即可立即更新视图的属性,但不会对其设置动画

    因此,最后,如果要为视图属性值的更改设置动画,则必须使用UIView。如下图所示设置动画。

    let view = MyView()
    
     UIView.animate(withDuration: 10) {
         view.layer.backgroundColor = UIColor.red.cgColor
         view.mySublayer.backgroundColor = UIColor.red.cgColor
     }
    

    希望有帮助