Solid solution to flexibly resize UIView based on

2019-07-23 22:11发布

Imagine you have four or so views, all width 100, different heights. You have a wrapper view W which holds them all.

A   |
B   |  W
C   |
D   |

the heights of the small views can change. At that time you want them all to move, float, appropriately, and resize W.

Now, I was just about to write a few lines of code to do this.

So .. (1) you'd have W find all the subviews and list them in order from top to bottom. Then (2) each time there is a change, you'd (3) reposition each of ABCD. the position of each one is the sum of the heights of the items above it, and (4) resize W to the sum of all heights.

Now that's all fine but -- idiots reinvent the wheel!

Am I missing something obvious in iOS? is there already a package everyone uses to do this all the time? Or something built in? What's the situation?

(Note that of course frustratingly, for our Android friends this is built in! And of course any web-html system does this automatically.)

What's the right engineering solution for iOS views here? For the record this is iOS7+ only, no old-fashioned stuffs need be covered, if it makes a difference. Cheers

1条回答
淡お忘
2楼-- · 2019-07-23 22:51

(1) you'd have W find all the subviews and list them in order from top to bottom. Then (2) each time there is a change, you'd (3) reposition each of ABCD. the position of each one is the sum of the heights of the items above it, and (4) resize W to the sum of all heights.

You can use constraints in Interface Builder for that whole process, no code required. Do this:

  • set the width of subview A to 100
  • constrain B, C, and D to match A's width
  • add vertical spacing constraints between A and B, B and C, and C and D to maintain their relative position
  • add a vertical spacing constraint between W (the superview, shown in gray) and A
  • add a vertical spacing constraint between W and D
  • add leading and trailing space constraints between W and view A

You'll end up with something that looks like this:

constraints

The constraints editor in Xcode isn't completely intuitive, but it is easy to use once you understand what you can and can't do with constraints in IB and when you need to use code to set up the constraints.

查看更多
登录 后发表回答