Question

In my app, I have a hierarchy like Main view -> UIScrollView - > UISearchBar. The search bar covers the whole width of screen. But when it switches to landscape the scrollview adjust itself according to landscape and cover whole screen but its subviews like UISearchBar width remain same as in portrait. Plus I'm using Autolayout and I've correctly set their constraints (Leading and Trailing, width (greater than equal to 320) etc) in storyboard.

Also I know there are several answers for this in SO but almost everyone is saying set width again in willAutororate. But I have around 15 subviews in UIScrollview which I think is not possible to set programatically (as increase LOC) plus I think Autolayout must have some solution to it.

Was it helpful?

Solution

try this : this problem will solve by constraints only. I created a project and by using correct constraints its working fine for me ,

here I am going to show you how to add correct constraint one by one :

  1. add scrollview and add constraints for scrollview only like in the screenshots :

enter image description here

2. now add search bar and add constraints for search bar too, 
here below you can find out complete constraints for scrollview and search together:

enter image description here

OTHER TIPS

Scrollviews don't play very well with constraints. Here's an approach using constraints and Interface Builder that worked for me for having a vertically scrolling scrollview that doesn't require any manual or content size finagling and works with rotation:

  • Scrollview in a view controller positioned with constraints
  • A container (UIView) that is a subview of the scrollview positioned with constraints pinning each edge to the superview
  • Add all your additional subviews to the container view instead. Use constraints. Exceed the height of the scrollview to get a vertically scrolling scrollview.

There is one trick however to get rotation resizing to work automagically:

  • You have to add an additional constraint to the container view to match its width to the UIScrollview's width. It's strange that you have to do this, since pinning each side to the scrollview should do the trick, but alas it won't work with rotation if you don't add the additional constraint.

Here's what I mean:

UIScrollView with constraints in Interface Builder

You could use UIViewAutoresizing mask (autoresizingMask property) of your subviews.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top