title: Swift : Animate CALayer
body: <p>In the code below I am trying to animate a <code>CALayer</code> from the left side of the screen to the right side of the screen as the user is holding down on the screen (longPressGestureRecognizer). When the user lifts their finger, the <code>CALayer</code> pauses.</p>
  
  <pre><code>var l = CALayer()
  var holdGesture = UILongPressGestureRecognizer()
  let animation = CABasicAnimation(keyPath: "bounds.size.width")
  
  override func viewDidLoad() {
      super.viewDidLoad()
      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){
  
      if(sender.state == .Began) { //User is holding down on screen
          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")
      }
      else { //User lifted Finger
          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
  }
  </code></pre>
  
  <p>I have two issues:</p>
  
  <ol>
  <li><p>When i print the width of the <code>CALayer</code> after the animation (when user lifts finger) its always 0. I animate the width, and its expanding, thus I do not know why it does not give me the new width of the <code>CALayer</code>.</p></li>
  <li><p>After the user lifts their finger, and then holds down again, the <code>CALayer</code> disappears. I need it to remain on the screen, and create another <code>CALayer</code>, I do not delete it in any way, so i do not understand why it is as well disappearing. I checked the memory the object still exists.</p></li>
  </ol>
  
  <p><strong>UPDATE to issue #2</strong> : I believe to create another <code>CALayer</code> I can't just add the layer again. I must either create a copy or create a <code>UIView</code> that I can add the layer to. I still do not understand why it is disappearing though.</p>