iosswiftloopsuiviewanimatewithduration

animateWithDuration one after another


I have a label that is initially positioned at the center of the screen. It currently transitions from the the center to the right end of the screen then autoreverses back to its position. I'd like to have it begin another animateWithDuration so that it continues from the center return to the left position of the screen then autoreverse back to the position and sequentially loop from there on after.

I have already attempted and successfully made the first half work but I'm not sure how to continue to the second portion where it begins the center->left transition and loop.

Swift 2.0 Code:

   func animateRight()
    {
        UIView.animateWithDuration(1.0, delay: 0.0, options: [ .Autoreverse, .CurveEaseInOut], animations: {
                label.center.x = self.view.frame.width/2
            }, completion: { finished in
                if finished {
                    label.frame.origin.x = 0.0
                    animateLeft()
                }
        })
    }

    func animateLeft()
    {
        UIView.animateWithDuration(1.0, delay: 0.0, options: [ .Autoreverse, .CurveEaseInOut], animations: {
                label.frame.origin.x = (self.view.frame.width/2) * -1
            }, completion: { finished in
                if finished {
                    label.center.x = self.view.frame.width/2
                    animateRight()
                }
        })
    }

    // Start process
    animateRight()

Solution

  • You should call the same animate with duration method you create for animating to right and call in completion. Something like this:

    func animateRight()
    {
        UIView.animate(withDuration: 1.0, delay: 0.0, options: [], animations: {
            self.label.center.x = self.view.frame.width
        }, completion: { finished in
            if finished {
                self.animateLeft()
            }
        })
    }
    
    func animateLeft()
    {
        UIView.animate(withDuration: 2.0, delay: 0.0, options: [ .autoreverse, .repeat, .curveEaseInOut, .beginFromCurrentState], animations: {
            self.label.frame.origin.x = 0.0
        }, completion: nil)
    }