Search code examples
iosswiftuipangesturerecognizer

returning View to it`s original position after panning


I have a view (chicken) that can be panned around an should return to it`s original position when released. Right now, the chicken just disappears when the panGesture ended.

Here is my code:

override func viewDidLoad() {
        super.viewDidLoad()

        // record original Position
        originalChickenPosition = chicken.center
        print(originalChickenPosition) // works fine

        view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePan:"))    
    }


    func handlePan(panGesture: UIPanGestureRecognizer){

        switch panGesture.state{

        case .Began:
            // start flying

        case .Changed:
            // follow the pan
            let dCenter = panGesture.translationInView(view)
            chicken.center = CGPointMake(chicken.center.x + dCenter.x, chicken.center.y + dCenter.y)
            panGesture.setTranslation(CGPointZero, inView: view)

        case .Ended:
            // fly back
            if originalChickenPosition != nil{
              chicken.center = originalChickenPosition!
            }

        default: break

        }   
    }

I found this : Returning view to original position after pan gesture, swift but it seems to be a different problem, I would be happy if my view would jump back.

Any suggestions apreciated.


Solution

  • There should be autolayouts set to the view. If YES then make sure you update constraints after you set the original position.

    func handlePan(panGesture: UIPanGestureRecognizer){
    
        switch panGesture.state{
    
        case .Began:
            // start flying
    
        case .Changed:
            // follow the pan
            let dCenter = panGesture.translationInView(view)
            chicken.center = CGPointMake(chicken.center.x + dCenter.x, chicken.center.y + dCenter.y)
            panGesture.setTranslation(CGPointZero, inView: view)
    
        case .Ended:
            // fly back
            if originalChickenPosition != nil{
              chicken.center = originalChickenPosition!
            }
            **self.chicken.setNeedsUpdateConstraints()**
            default: break
    
        }   
    }