Search code examples
iosuiscrollviewautolayout

How to configure a UIScrollView content size to have a fixed width and a dynamic height?


I have a UIScrollView contained in another container view with constraints set to take all the space of the container view. That is to say that I don't have a fixed width or height on the scroll view.
In my scroll view I programmatically add subviews. Each subview (content view) is loaded from a xib.
In the xib I set an arbitrary size to the root view (500x500) but I would like that view width to be automatically resized to the scroll view width (the scroll view width being the container width).
I don't want the user to be able to scroll horizontally.

I tried different solutions always resulting in the scroll view being scrollable horizontally.
I tried to tweak the content view hugging and compression property to different values on the horizontal axis with no success.

I don't want to set fixed widths on my views because I want them to take the width of the container view.

Thanks in advance if you have any suggestions.


Solution

  • Late answer with what I came up with at that time.
    As I'm using Autolayout, VChemezov answer is not really satisfying.

    My content views have a top, bottom, leading, width set of constraints. (width instead of trailing which is what I was doing in the first place but it was not working).

    So now I have something like this:

            NSLayoutConstraint *leading = [NSLayoutConstraint
                                           constraintWithItem:messageView
                                           attribute:NSLayoutAttributeLeading
                                           relatedBy:NSLayoutRelationEqual
                                           toItem:self.conversationScrollView
                                           attribute:NSLayoutAttributeLeading
                                           multiplier:1.0f
                                           constant:0.0f];
            NSLayoutConstraint *width = [NSLayoutConstraint
                                            constraintWithItem:messageView
                                            attribute:NSLayoutAttributeWidth
                                            relatedBy:NSLayoutRelationEqual
                                            toItem:self.conversationScrollView
                                            attribute:NSLayoutAttributeWidth
                                            multiplier:1.0f
                                            constant:0.0f];
            [self.conversationScrollView addConstraints:@[ top, leading, width ]]; 
    

    With the width of the content view equal to the width of the scroll view.