Center contents of UIScrollview when using autolay

2019-06-17 16:07发布

I'm using autolayout in my project and I have a scrollview that has a button centered in it. I have gotten the scrollview to scroll, but not to take up the entire screen.

I've tried to follow the tutorial here: https://developer.apple.com/library/ios/technotes/tn2154/_index.html, as well as I have checked out a few similar questions on here. The issue is that I want the contents of the scrollview to center, rather than be pinned to the top/bottom/left/right.

Here is my view hierarchy:

enter image description here

Could you please help me out?

1条回答
何必那么认真
2楼-- · 2019-06-17 16:20

You have added constrains between your scroller view and its super view. These constrains determines the frame of the scroll view. You can think of the scroll view as a window, through which you can see the the contents behind. The frame is the just the size of the window. Of course, you can slide the window, which gives you the sights of parts of the contents.

Now you have the size of the window, but you also need to tell Xcode the size of the contents. If you just say put everything in the middle without telling the width, how can Xcode know where is the middle?

So, you have to tell the width (as well as height). Let's think about a simple example, how to center a single label in a scrollview.

enter image description here

You should first pin the edges of the scroll view to its super view just as what you did. After that you should add constraints between the edges of the label and the edges of the scroll view, besides, you should also add the with and the height constraints of the label.

The leading space, the trailing space and the width together give the with of the contents, while the top space, bottom space and the height together give the height of the contents.

|---leading space---|label width|---trailing space---|

|---------- content with of the scroll view -------------|

But you may want to set the with of the content view equal to the with of your screen, then you need to do some programming. Set there outlet properties in you code

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *trailingSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *width;

In your viewWillLayoutSubviews do this

CGFloat contentWidth = self.view.frame.size.width;
CGFloat horiPadding = (contentWidth - self.width.constant) / 2;
_trailingSpace.constant = horiPadding;
_leadingSpace.constant = horiPadding;

Now you the label is at the horizontal center of you scroll view! Your scroll view has already knew the with of its contents, so you don't need to do this for any other view you added in your scroll view: you can just add the center constraint.

You can also do the same thing for the height.

enter image description here

enter image description here

查看更多
登录 后发表回答