Search code examples
iosobjective-cnslayoutconstraint

iOS - Change vertical spacing between 2 UIView


I have 3 different scenarios for a single XIB File.

Here is the XIB File, I have 3 different UIView.

enter image description here

My scenarios are :

  • View 2 is displayed and View 1 and View 3 are hidden.
  • View 1 and View 3 are displayed and View 2 is hidden.
  • View 1, View 2 and View 3 are displayed.

My question is concerning the second case, where only View 1 and View 3 are displayed.

I can hide View 2, but I would like for this specific case to make View 1 and View 3 closer.

enter image description here

How can I do it ?

I tried with something like this but without success.

-(void)setConstraints {

    [NSLayoutConstraint constraintWithItem:_infoView1
                                 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
                                    toItem:_infoView3 attribute:NSLayoutAttributeBottom
                                multiplier:1.0 constant:0];
}

Solution

  • Step 1 : Connect top constraint of view 2 with view 1 similarly connect top constraint of view 3 with view 2 then create and map height constraints for view 1 view 2 and view 3.
    
    Step 2 : For scenarios mentioned in question, put conditions for your cases and do steps mentioned below
    
    1) View 2 is displayed and View 1 and View 3 are hidden.
    set height constraint for view 1 and view 3 to zero 
    heightConstraintOfView1.constant = 0
    heightConstraintOfView3.constant = 0
    
    2) View 1 and View 3 are displayed and View 2 is hidden.
    set height constraint for view 2 to zero 
    heightConstraintOfView2.constant = 0
    
    3) View 1, View 2 and View 3 are displayed.
    Don’t set height constraint for any view to zero.
    

    I assume all other constraints are set properly.