What is the purpose of UIView's autoresizingMa

2019-03-10 22:47发布

After reading about UIView's autoresizingMask on SO and developer.apple.com I'm still unclear what the purpose is. What's a situation where setting this property is necessary?

2条回答
等我变得足够好
2楼-- · 2019-03-10 22:57

Yes, it is often necessary to set it if you don't want to resize the views manually. Note that it is mostly useful for subviews (i.e. those views that don't take the whole screen) rather then the main view of your app.

Views typically may need resizing if:

  • the device is rotated
  • an extra view (say, an ad) is added to the view, so the existing subviews have less available space.

For example, suppose if you have a view with two buttons on it, one in the top-left corner, another in the top-right corner. In order for the buttons to get wider when the view transitions from portrait to landscape, you need to set the FlexibleLeftMargin to the right button, FlexibleRightMargin to the left button.

Edit: autoresizingMask is also the first thing to look at if you see weird holes or overlaps when device is rotated or a new subview is added. Quite often the proper setting of these masks for subviews can get you a nice looking view in both orientations without having to lay out subviews manually - but usually it takes some experimenting.

Edit2: (since this is still gathering upvotes) Autoresizing masks are now mostly superseded with "Auto Layout", which allows for much more flexible constraints on views' sizes and positions. That being said, translatesAutoresizingMaskIntoConstraints is still occasionally useful for dynamically added views.

查看更多
老娘就宠你
3楼-- · 2019-03-10 22:57

The purpose is that UIView properly shifts and resizes when it's superview changes due to resizing, orientation change, showing editing controls in tableview cells etc.

查看更多
登录 后发表回答