3

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

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
}

我有两个问题:

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

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

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

4

1 回答 1

7

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

如果您想将原点固定在左侧,则需要先设置图层的锚点:

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)
  }
}
于 2016-01-11T05:25:16.330 回答