Max Hudson
Max Hudson

Reputation: 10206

Scroll to scrollview page while scrollview is being resized

I've got a scrollview with paging disabled. It has a number of subviews. Each of those has a width constraint and are constrained to each other and the scrollview, so when the subviews grow, the scrollview content area grows.

When a subview is tapped, I run the following code:

var page = subView.tag

for scrollViewSubViewWidthConstraint in scrollViewSubViewWidthConstraints {
    //this results in the subview being larger than it previously was
    scrollViewSubViewWidthConstraint.constant = self.view.frame.width
}

UIView.animateWithDuration(0.35) {
    self.view.layoutIfNeeded()
}

scrollView.pagingEnabled = false
scrollView.setContentOffset(CGPoint(x: self.view.frame.width * CGFloat(page), y: 0), animated: true)

This code is intended to:

  1. Resize the subviews so they are the width of a 'page'
  2. Enable paging on the scrollview
  3. Scroll to the correct page smoothly

Unfortunately it not only doesn't scroll to the correct page, seemingly because it's trying to calculate the amount to scroll while the constraints are being updated, but it does so in an unappealing fashion animation wise.

If I change my code to this (cutting out the animation) it still doesn't work:

self.view.layoutIfNeeded()

scrollView.pagingEnabled = true
scrollView.setContentOffset(CGPoint(x: self.view.frame.width * CGFloat(page), y: 0), animated: false)

This works, but it's not animated, and it's delayed - neither of which are okay.

self.view.layoutIfNeeded()

UIHelper.delay(0.1, closure: { () -> () in //helper function that executes code after a given delay...
    self.scrollView.pagingEnabled = true
    scrollView.setContentOffset(CGPoint(x: self.view.frame.width * CGFloat(page), y: 0), animated: true)
})

Upvotes: 2

Views: 383

Answers (1)

DigitalBrain_DEV
DigitalBrain_DEV

Reputation: 1103

Maybe the workaround can be to set the contentOffset into the animation Block

    UIView.animateWithDuration(0.35) {
        self.view.layoutIfNeeded()
        scrollView.setContentOffset(CGPoint(x: self.view.frame.width * CGFloat(page), y: 0), animated: false)
    }

Upvotes: 1

Related Questions