2

I want variable height of view in different screens. Let's say, I want view's height 80px in 3.5 inch screen.

100px in 4.0 inch screen

120px in 4.5 inch screen

and 140 in 4.7 inch screen.

What is the best way to do achieve it with autolayout ?

Haris
  • 1,822
  • 2
  • 22
  • 44

3 Answers3

0

Align the view with AutoLayout for example to the top and sides to it's superview, but set a fixed height constraint like this:

enter image description here

Then create an outlet for the height constraint. In your class you can change the height now with:

self.myHeightConstraint.constant = 120;

edit: well you have to deselect the "Width" checkmark, didn't notice it was selected when I created the screenshot...

Thyraz
  • 2,412
  • 2
  • 21
  • 23
0

Create an IBOutlet onto the height constraint of the view. After, you will be able to set the constraint constant in code (after checking for the screen height). Of course you will also have to set your other constraints too, however keep in mind that your view height will be changing (or commit constraints with possible conflicts in mind)

ex (in swift):

let height = self.view.frame.size.height
if height == 568 { //iPhone 5 size

     self.viewHeight_Constraint.constant = 120.0
     self.myView.layoutIfNeeded();

}

I've had success with layoutIfNeeded, but look at the answer here for justification.

Community
  • 1
  • 1
Nate Lee
  • 2,842
  • 1
  • 24
  • 30
0

If you don't need so much accuracy i think best way is to use relation multiplier. If screen will grow you view will grow to.

You can do this by code or Interface Builder

- (void) viewWillAppear:(BOOL)animated
{

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:upperview
                                                             attribute:NSLayoutAttributeHeight 
                                                             relatedBy:0 
                                                                toItem:self.view
                                                             attribute:NSLayoutAttributeHeight
                                                            multiplier:.5 
                                                              constant:0];
[self.view addConstraint:constraint];
}
Community
  • 1
  • 1