下面的代码创建一个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()
}
我遇到的问题是变量“layer”只能暂停(当通过“pauseLayer”函数传递时)如果它是一个全局变量!我不知道为什么!我想在“handleLongPress”函数中声明变量。这样做的原因是因为每次识别longPressGestureRecognizer时,我都需要声明一个同名的新变量。我尝试过使用“inout”通过引用传递但好像不起作用谁来帮帮我。
3条答案
按热度按时间nfeuvbwi1#
暂停层
我给你的奖金恢复功能:D
rta7y2nd2#
使用此修改代码:
cczfrluj3#
这里是暂停你的动画功能,并再次在同一时间重新启动