Swift:在CABasicAnimation

时间:2016-01-13 18:18:55

标签: ios swift calayer cabasicanimation

您在下面看到的代码会创建一个CALayer(矩形形状),并在用户按住屏幕时从左到右设置动画(' longPressGestureRecognizer')。当他们抬起手指时,CALayer停止动画,它被推入阵列,当他们再次按住屏幕时,会创建另一个CALayer。您可以直接在新项目中复制和粘贴代码:

    //Global Variables
var layer: CALayer?
var holdGesture = UILongPressGestureRecognizer()
let animation = CABasicAnimation(keyPath: "bounds.size.width")
var layerHolder = [CALayer]()
var widthIndex = CGPoint(x: 0, y: 0)
var nextXOffset = CGFloat(0.0)
var checkIfFull = CGFloat()
var colorIndex : Int = 0
let barColors = [
    //Red
    UIColor(red: 0.969, green: 0.49, blue: 0.443, alpha: 1),
    //Orange
    UIColor(red: 0.984, green: 0.647, blue: 0.431, alpha: 1),
    //Pink
    UIColor(red: 0.894, green: 0.592, blue: 0.698, alpha: 1),
    //Purple
    UIColor(red: 0.851, green: 0.6, blue: 0.957, alpha: 1),
    //Yellow
    UIColor(red: 0.98, green: 0.875, blue: 0.455, alpha: 1),
    //Green
    UIColor(red: 0.49, green: 0.792, blue: 0.616, alpha: 1),
    //Blue
    UIColor(red: 0.553, green: 0.71, blue: 0.906, alpha: 1)]



func setUpView(){

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

}


func handleLongPress(sender : UILongPressGestureRecognizer){

    if(sender.state == .Began) {

        let newLayer = CALayer()
        newLayer.frame = CGRect(x: nextXOffset, y: 0, width: 0, height: 10)
        newLayer.backgroundColor = barColors[colorIndex % 7].CGColor

        print("before \(nextXOffset)")
        newLayer.anchorPoint = widthIndex
        animation.fromValue = 0
        animation.toValue = self.view.bounds.width * 2 - nextXOffset
        animation.duration = 5
        self.view.layer.addSublayer(newLayer)

        print("Long Press Began")
        newLayer.addAnimation(animation, forKey: "bounds.size.width")

        layer = newLayer
    }
    else {
        print("Long press ended")

        if let layer = layer {
            print("after \(nextXOffset)")

            pauseLayer(layer)

            layer.frame = layer.presentationLayer()!.frame
            nextXOffset = CGRectGetMaxX(layer.frame)
            layerHolder.append(layer)

            colorIndex++

        }
    }
}

我的问题是,当创建新的CALayer并制作动画时,它会从两侧增长,而不仅仅是增长到右侧。我需要他们彼此并排,一个向右移动而另一个离开。在我让它们互换颜色之前,我没有注意到它。经过一些研究,我相信从最后一个CALayer停止的位置设置一个锚点是正确的方法。我一直在努力实现这一目标但是还没有能够做到这一点。帮我?请?

UPDATE :我相信如果我使用nextXOffset作为锚点,我可能会这样做,但它的类型是CGfloat而不是CGPoint。求救!

1 个答案:

答案 0 :(得分:0)

这很有用,我真傻。将'widthIndex'保持在(0,0)允许它从最后一个栏停止的位置开始。代码有效。