Search code examples
iosautolayoutinterface-builder

uiview.trailing = trailing not working in landscape


I want a textfield to extend (almost) all the way to the trailing margin. It works perfectly in portrait, but when I rotate to landscape, the textfield doesn't extend as far as I've specified.

Here is my project

and here is how it looks in landscape

As you can see, the textfield doesn't extend to all the way to the trailing margin + 44.

Thanks in advance for your help


Solution

  • These fields are in a scroll view, which is causing this. The scrollview starts with the default values in Interface Builder, and then the scrollview prefers to shrink it's contentSize rather than expand the text field. Set the scrollview's background color to something and you'll see this.

    Making one axis of a scrollview fixed to the frame, size of the scrollview for one-dimensional scrolling is surprisingly hacky for something that scroll view clients want probably 90% of the time. The reason is that superview constraints in IB act on the scrollview's frame, which is what you want to size the frame, but there's no way in IB to constrain a superview to the scroll view's content size.

    To make the scroll view scroll in one direction, first get the two items on either side that have constraints to the scrollview margins. In your case, the UILabel leading and UITextField trailing. Add constraints connecting them identically to the topmost UIView in the hierarchy. They will then hold the sides of the scrollview into place.