在下面的代码中,我正在尝试通过用户按住屏幕(longPressGestureRecognizer)来使一个CALayer从屏幕左侧动画到右侧。当用户松开手指时,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
}
我有两个问题:
- 当用户松开手指后,我打印
CALayer
的宽度时,它总是为0。我正在对宽度进行动画处理,并且它正在扩展,因此我不知道为什么它不会给我CALayer
的新宽度。 - 当用户松开手指后再次按下时,
CALayer
会消失。我需要它继续留在屏幕上并创建另一个CALayer
,我没有以任何方式删除它,因此我不明白它为什么还会消失。我检查了对象的内存,它仍然存在。
问题2的更新: 我相信要创建另一个 CALayer
,我不能只添加图层。我必须复制或创建一个 UIView
,然后将图层添加到其中。但我仍然不理解为什么它会消失。