【发布时间】:2016-01-12 04:39:54
【问题描述】:
您在下面看到的代码创建了一个 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”通过引用传递,但它似乎没有用。有人可以帮忙吗?请。
【问题讨论】:
标签: ios xcode swift calayer caanimation