SFlow SFlow - 3 years ago 160
iOS Question

Centering a sub view in UIScrollView progammatically

I see a bunch of similar questions on SO but none that solve my problem.

I am adding a UIView as a subview of UIScrollView. The UIView has 3*scrollView.width and 3*scrollView.height. So I set the contentSize of the UIScrollView accordingly. When the app is launched I want to scrollView window to be in the middle of the subView, something like this --

-------------------
| |
| ________ |
| | | |
| | | |
| ------- |
| |
-------------------


The inside window is supposed to be the scrollView and also the portion of the UIView the user sees, when the app launches. However what ever I can't make it happen.
The scrollView is always set to origin (0,0)

I did this -

let margins = view.layoutMarginsGuide
scrollView.leftAnchor.constraint(equalTo: margins.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: margins.rightAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: 0).isActive = true
scrollView.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true

scrollView.center = self.view.center // view is the base view of which scrollView is a subview of.
subView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: -1*scrollView.frame.width)
subView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: -1*scrollView.frame.height)

Answer Source

As per my understanding, you have UIScrollView and UIView inside that and scroll with content size 3 times of view height/width and when app launches, you need the center of the scroll.

In that case, I try to close as much possible using storyboard so what I did,

  1. Added UIScrollView with constraints

Top space to SuperView, Trailing to SuperView, Leading and Bottom to superView.

  1. Added UIView inside UIScrollView with constraints.

Top space to SuperView, Trailing to SuperView, Leading and Bottom to superView with Height and Width Equals to UIView (that we have on top of UIScrollView) with multiplier 3 times.

That's all from the storyboard, now the only thing we need to set is setContentOffset for UIScrollView like this.

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let contentOffsetX = (scrollView.contentSize.width/2) - (view.bounds.width/2)
        let contentOffsetY = (scrollView.contentSize.height/2) - (view.bounds.height/2)

        scrollView.setContentOffset(CGPoint(x: contentOffsetX, y: contentOffsetY), animated: true)
    }

And we are done. I hope it will help you. You can also find the codebase at Github.com

Happy Learning.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download