-1
你看到下面的代碼創建一個CALayer的(長方形),從左至右動畫(您可以直接複製和粘貼代碼在新的項目):斯威夫特:暫停CABasicAnimation的CALayer的
//Global Variables
var layer = CALayer()
var holdGesture = UILongPressGestureRecognizer()
let animation = CABasicAnimation(keyPath: "bounds.size.width")
func setUpView(){
self.view.addGestureRecognizer(holdGesture)
holdGesture.addTarget(self, action:"handleLongPress:")
}
func handleLongPress(sender : UILongPressGestureRecognizer){
//NEED IT HERE
//var layer = CALayer()
layer.frame = CGRect(x: 0, y: 0, width: 0, height: 10)
layer.backgroundColor = UIColor.redColor().CGColor
animation.fromValue = 0
animation.toValue = self.view.bounds.width * 2
animation.duration = 5
self.view.layer.addSublayer(layer)
if(sender.state == .Began){
print("Long Press Began")
layer.addAnimation(animation, forKey: "bounds.size.width")
}
else{
print("Long press ended")
pauseLayer(layer)
}
}
func pauseLayer(layer : CALayer){
let pausedTime : CFTimeInterval = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
layer.speed = 0.0
layer.timeOffset = pausedTime
}
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()
}
我遇到的問題是變量「層」只能暫停(當通過「pauseLayer」函數傳遞時),如果它是全局變量!我不知道爲什麼!我想在「handleLongPress」函數中聲明變量。原因是因爲我需要在每次識別longPressGestureRecognizer時聲明一個具有相同名稱的新變量。我曾嘗試通過引用與「inout」,但它似乎沒有工作。有人可以幫忙嗎?請。
你是了不起的MY GOOD SIR! – OriginalAlchemist
我的好先生,你有沒有機會知道如何跟蹤圖層的寬度?我嘗試「layer.bounds.size.width」來打印圖層的寬度,但它總是返回0.任何想法? – OriginalAlchemist
newLayer.frame = CGRect(x:0,y:0,width:0,height:10)在這裏給出適當的寬度。 –