Swift:动画CALayer

时间:2016-01-11 01:50:57

标签: ios swift animation calayer uilongpressgesturerecogni

在下面的代码中,当用户按住屏幕(longPressGestureRecognizer)时,我试图将CALayer从屏幕左侧动画到屏幕右侧。当用户抬起手指时,CALayer会暂停。

var l = CALayer()
var holdGesture = UILongPressGestureRecognizer()
let animation = CABasicAnimation(keyPath: "bounds.size.width")

override func didReceiveMemoryWarning(){
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    setUpView()

}

func setUpView(){
    l.frame = CGRect(x: 0, y: 0, width: 0, height: 10)
    l.backgroundColor = UIColor.redColor().CGColor

    self.view.addGestureRecognizer(holdGesture)
    holdGesture.addTarget(self, action:"handleLongPress:")

}

func handleLongPress(sender : UILongPressGestureRecognizer){

    //User is holding down on screen
    if(sender.state == .Began){
    print("Long Press Began")
    animation.fromValue = 0
    animation.toValue = self.view.bounds.maxX * 2
    animation.duration = 30
    self.view.layer.addSublayer(l)
    l.addAnimation(animation, forKey: "bounds.size.width")

    }

    //User lifted Finger    
    else{
        print("Long press ended")
        print("l width: \(l.bounds.size.width)")
        pauseLayer(l)
    }
}

func pauseLayer(layer : CALayer){
    var pausedTime : CFTimeInterval = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
    layer.speed = 0.0
    layer.timeOffset = pausedTime

}

我有两个问题:

1)当我在动画之后打印CALayer的宽度时(当用户抬起手指时)它始终为0.我设置宽度的动画,并且它的扩展,因此我不知道为什么它不会给我新的宽度CALayer。

2)用户抬起手指然后再次按住后,CALayer消失。我需要它保留在屏幕上,并创建另一个CALayer,我不以任何方式删除它,所以我不明白为什么它也消失了。我检查了对象仍然存在的内存。

更新发布#2 :我相信创建另一个CALayer我不能再次添加图层,我必须创建一个副本或创建一个我可以添加图层的UIView。我仍然不明白它为什么会消失。

1 个答案:

答案 0 :(得分:6)

基本上,当用户按住时,您正尝试调整图层的大小。这是一个可用于调整给定图层大小的函数:

如果您希望将原点挂在左侧,则需要先设置图层的锚点:

layer.anchorPoint = CGPointMake(0.0, 1);

func resizeLayer(layer:CALayer, newSize: CGSize) {

    let oldBounds = layer.bounds;
    var newBounds = oldBounds;
    newBounds.size = size;


    //Ensure at the end of animation, you have proper bounds
    layer.bounds = newBounds

    let boundsAnimation = CABasicAnimation(keyPath: "bounds")
    positionAnimation.fromValue = NSValue(CGRect: oldBounds)
    positionAnimation.toValue = NSValue(CGRect: newBounds)
    positionAnimation.duration = 30
} 

在你的情况下,我不知道你在哪里恢复暂停的层。还要观察每次用户点击时,在handleLongPress方法中添加一个新动画!这将产生不良影响。理想情况下,您只需要第一次启动动画,然后再恢复之前开始的暂停动画。

//Flag that holds if the animation already started..
var animationStarted = false

func handleLongPress(sender : UILongPressGestureRecognizer){

  //User is holding down on screen
  if(sender.state == .Began){

    if(animationStarted == false){
      let targetBounds =  CalculateTargetBounds() //Implement this to your need
      resizeLayer(layer, targetBounds)
      animationStarted = true
    }else {
      resumeLayer(layer)
    }
  }else {
    pauseLayer(layer)
  }
}