How to remove space of hidden UIImage?

1.8k views Asked by At

I'm stuck that I don't know how to remove spacing of hidden UIImage. Purpose is If flag is true, UIImage will be displayed and if flag is false, UIImage is hidden but space of this hidden image is still there.

I'm using Auto Layout.

enter image description here

2

There are 2 answers

0
dstudeba On BEST ANSWER

If you are using Auto Layout and Storyboard you can set create an IBOutlet as a property of your Controller class. You then hook that up to the width constraint of the UIImage. In your code when the UIImage is hidden you set the IBConstraint to 0. When it is shown, you set the IBConstraint back to the normal width.

(in Controller.h)

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintImageWidth;

(in Controller.m) (pseudo code)

if(hidden){
     constraintImageWidth.constant = 0;
}
else{
     constraintImageWidth.constant = 30;
}

There should also be a horizontal constraint between the left side of the label and the right side of the image set up in the Storyboard.

enter image description here

Here is where you would check the width box to add the width constraint.

enter image description here

Here is where you would connect the referencing Outlet to the IBOutlet on your controller

1
Holmes On

The easiest and most effective way to handle this is using Stack Views. Insert both the images in a horizontal stack view and stack view will internally take care of the spacing. Additional properties like alignment, spacing can be tweaked as per requirement. Keep in mind that you will have to re-establish the constraints between stack view and adjacent elements since once the views are added to a stack view all if its constraints are cleared