2016-04-08 104 views
0

我正在使用动画在两种颜色之间淡化按钮,并且在按下按钮时需要获取其当前颜色。在Swift中的动画中获取UIView的颜色?

这里的动画代码:

UIView.animateWithDuration(speed, delay: 0.0, options:[UIViewAnimationOptions.Repeat, UIViewAnimationOptions.Autoreverse, UIViewAnimationOptions.AllowUserInteraction, UIViewAnimationOptions.CurveEaseOut], animations: { 
      targetView.layer.backgroundColor = self.randomColors(40).CGColor 
      targetView.layer.backgroundColor = self.randomColors(250).CGColor 

      }, completion: nil) 

阅读使用targetView.layer.backgroundColor颜色每次,不是颜色在那个特定的时刻给了我同样的结果。我已经尝试了几个函数来获得屏幕上特定像素的颜色,但它们只是每次都返回相同的颜色。

按下按钮后不需要继续动画,我只需要在按下按钮时获取颜色。

任何帮助将是惊人的,谢谢!

回答

1

您可以使用presentationLayer获得给定图层的屏幕状态的近似值,包括当前正在运行的任何动画。它返回一个可选的AnyObject - 所以你必须确保你正确地解开它。

例如:

if let presentationLayer = targetView.layer.presentationLayer() as? CALayer { 
    let currentBackgroundColor = presentationLayer.backgroundColor 
} 

注意从这里返回层是副本 - 因此它的任何修改将不会被其他地方反映出来。

+0

谢谢!那正是我所追求的。非常感激。 – Stephen

+0

@Stephen高兴地帮助:) – Hamish