UIScrollViews subviews not resizing themselves on

2019-04-17 00:31发布

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.

3条回答
孤傲高冷的网名
2楼-- · 2019-04-17 01:08

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

查看更多
smile是对你的礼貌
3楼-- · 2019-04-17 01:14

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

查看更多
戒情不戒烟
4楼-- · 2019-04-17 01:16

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

查看更多
登录 后发表回答