tjlsmith
tjlsmith

Reputation: 85

UIScrollView Paging with Animation Completion Handler

I have a UIScrollview with buttons that I use for paging right and left:

@IBAction func leftPressed(sender: AnyObject) {

    self.scrollView!.setContentOffset(CGPointMake(0, 0), animated: true)
} 

I'd like to perform an action after the scrollview has finished the paging animation. Something like:

@IBAction func leftPressed(sender: AnyObject) {

    self.scrollView!.setContentOffset(CGPointMake(0, 0), animated: true)

    secondFunction()
}

The above code doesn't work because the second function runs before the scrollview is finished animating the offset. My initial reaction was to use a completion handler but I'm not sure how to apply one to the setContentOffset function. I've tried:

func animatePaging(completion: () -> Void) {

    self.mainScrollView!.setContentOffset(CGPointMake(0, 0), animated: true)

    completion()
}

with the call

animatePaging(completion: self.secondFunction())

But I get the error "Cannot invoke 'animatePaging' with an argument list of type '(completion())'. Any thoughts?

Upvotes: 2

Views: 3925

Answers (2)

T. Suwanwigo
T. Suwanwigo

Reputation: 1

Update from joern answer - Swift 4.2

UIView.animate(withDuration: 0.5, animations: { [unowned self] in
   self.scrollView.contentOffset = .zero
}) { [unowned self] _ in
   self.secondFunction()
}

Upvotes: 0

joern
joern

Reputation: 27620

The problem is that you need a completion handler for the scrolling animation itself. But setContentOffset(_:animated:) does not have a completion handler.

One solution would be that you animate the scrolling yourself using UIView's static function animateWithDuration(_:animations:completion:). That function has a completion handler that you can use:

UIView.animateWithDuration(0.5, animations: { () -> Void in
        self.scrollView.contentOffset = CGPointMake(0, 0)
    }) { (finished) -> Void in
        self.secondFunction()
    }

Upvotes: 4

Related Questions