问题
I have a UIView
(the red one in the image) I can pan in the x-axis. I can return the view back to the original position but I want to return to that position as though it's being pulled by a light spring, or sort of easing back to the original position with some sort of deceleration.
At the moment it weirdly jumps back to that position.
This is my relevant code and an image is attached to show the view in it's maximum position.
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Ended {
print(backgroundView.center.x) //120.0
print(backgroundView.center.y) //64.0
let xDivision = Double(backgroundView.center.x/120.0)
print(xDivision)
recognizer.view?.center = CGPointMake(120.0, 64.0)
self.view.frame = CGRectMake(backgroundView.center.x, 0, self.view.frame.width , self.view.frame.height)
UIView.animateWithDuration(xDivision, delay: 0.0, usingSpringWithDamping: 2.0, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.view.center.x = 120.0
}, completion: { (true) in
print("Animation Complete")
print(self.backgroundView.center.x)
})
}
let translation: CGPoint = recognizer.translationInView(self.view)
//recognizer.view?.center = CGPointMake((recognizer.view?.center.x)!, (recognizer.view?.center.y)! + translation.y)
recognizer.setTranslation(CGPointMake(0, 0), inView: self.view)
var center: CGPoint = (recognizer.view?.center)!
print(center.x)
center.x += translation.x
if center.x < 50.0 || center.x > 320.0 {
return
}
recognizer.view?.center = center
}
Any ideas on how I can achieve that. A good example of this animation is this app - http://rise.simplebots.co
Thanks.
回答1:
If you are using Auto Layout, changing the frame or center properties can cause problems. Have you thought about just changing the constraint's constant? Like:
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
switch recognizer.state {
case .Began:
//do something
case .Changed:
let translation = recognizer.translationInView(self.view)
self.leftContraint.constant = self.leftContraint.constant + translation.x
recognizer.setTranslation(.zero, inView: self.view)
case .Ended:
UIView.animateWithDuration(1,
delay: 0,
options: .CurveEaseOut,
animations: {
self.leftContraint.constant = //your value
self.view.layoutIfNeeded()
},
completion: nil)
default: ()
}
}
That helped me with a similar problem.
来源:https://stackoverflow.com/questions/36502801/returning-view-to-original-position-after-pan-gesture-swift