Satyam Satyam - 1 year ago 117
iOS Question

iOS - Using storyboard and autolayout to center the UIScrollView

I'm creating iOS app using story board and auto layout so that it will work good on both iPhone4 and iPhone5. Below is the screen shot of the view that I'm creating using story board.

enter image description here

In the above image, I want to keep the scroll view in the middle from leading edge of superview and the right table view. I dont want the scroll view to increase its width in iPhone5. I tried different combinations of constraints, but I couldn't achieve it.

Can some suggest me what are all constraints that I've to set for scroll view so that it will be in center.

Answer Source

You will need to do this by adding an additional view to the screen.

At the moment you have...

- UIView (main view)
    | - scrollView
    | - tableView

You should put the scroll view inside another view like this...

- UIView (main view)
    | - UIView (spacer View)
    |    | - scrollView
    | - tableView

Now what you can do is have these constraints...

spacer view leading edge constraint to super view = 0
spacer view trailing edge to table view leading edge = 0
table view width = (whatever the width is)
table view trailing edge to super view = 0

This will lay out the spacer view and the table view so that the spacer view will grow.

Now you need to add...

scroll view width = x
scroll view height = y
scroll view centered vertically in super view
scroll view centered horizontally in super view.

Now, because the scroll view's super view is the spacer view then it will always be centered in between the table view and the rest of the space.

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