在选择UITableViewCell上旋转图像

时间:2017-01-08 14:16:59

标签: ios uitableview animation

我试图在选择UITableViewCell上设置图像动画,图像是UITableViewCell的子图像,但它在旋转后返回到默认状态,这是我的代码。

override func setSelected(_ selected: Bool, animated: Bool) {

    if selected {
        super.setSelected(selected, animated: animated)
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnimation.fromValue = 0.0
        rotationAnimation.toValue =  (180.0 * CGFloat(M_PI)) / 180.0
        rotationAnimation.duration = 0.45

        self.updownImage.layer.add(rotationAnimation, forKey: nil)
    }


    // Configure the view for the selected state
}

1 个答案:

答案 0 :(得分:1)

您应该在添加动画之前立即将图层的变换设置为最终值。

CABasicAnimation实际上不会更改图层的属性,它只是设置图层的“表示层”以显示更改的外观。动画完成后,表示层将被隐藏,图层将恢复为非动画状态。通过在添加动画之前将图层设置为最终状态,在移除动画时,图层将显示为最终状态。

编辑:

这是对现有代码的一个非常简单的更改:

override func setSelected(_ selected: Bool, animated: Bool) {

  if selected {
    super.setSelected(selected, animated: animated)
    let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
    rotationAnimation.fromValue = 0.0

    //Put the angle in a constant so we can use to create a transform
    let angle = (180.0 * CGFloat(M_PI)) / 180.0
    rotationAnimation.toValue =
    rotationAnimation.duration = 0.45

    self.updownImage.layer.add(rotationAnimation, forKey: nil)

    //Create a transform for our rotation
    let transform = CATransform3DMakeRotation(angle, 0, 0, 1)

    //install the transform on the layer so the change is active after 
    //the animation completes
    layer.transform = transform
  }
}