Nam
Nam

Reputation: 1876

UIView expand but not overlap

I have a simple design question but can't seem to find the simplest answers.

Having say 10 UIViews aligned from top to bottom with no overlap. If I want to expand the height of one of them, how to I move the others so no overlapping occurs?

Here's my three thoughts, love to hear yours:

  1. Calculate each views origin y. Very messy I think.
  2. Use tableview. Seems to complex to solve a simple problem. And maybe old school since tables are old school in html. But more clean.
  3. Use constraints on all views. Seems simple and clean, but maybe a bit to complex to work with?

Have I forgotten anything obvious?

Regards

Upvotes: 0

Views: 59

Answers (1)

JaredH
JaredH

Reputation: 2398

I would certainly go with (3) for a few reasons:

  • Flexibility - literally: You'll be able to describe what you want to happen and let AutoLayout take care of the nitty-gritty calculations.
  • Flexibility - figuratively: You won't have to worry (as much) about your application displaying correctly on a variety of different devices.

Yes, AutoLayout can be a bit more complex to work with at times, especially in the beginning, but I promise you: it's worth it in the long run.

Here's some code to get you started. The below constraints are for 5 views. The first UIView will have a height of greater than or equal to myViewHeight, which is defined below to be 20. The subsequent 4 views will be equal to myViewHeight.

[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myView(>=myViewHeight)][_myView(==myViewHeight)][_myView(==myViewHeight)][_myView(==myViewHeight)][_myView(==myViewHeight)]-|"
                                                           options:0
                                                           metrics:@{@"myViewHeight": @20}
                                                             views:NSDictionaryOfVariableBindings(_myView)]];

Upvotes: 1

Related Questions