LS_
LS_

Reputation: 7129

Programmatically remove UILabel that has autolayout from View

I parse Json data and I set it on some UILabels, What I want is that when there's no text for a specific label It has to be removed from the UIView, I tried with 2 methods but with no results because the labels has constraints. What I tried is:

Set their frame to 0 and the height constraint to 0

CGRect noFrame = _prepTime.frame;

noFrame.size.width = 0;
noFrame.size.height = 0;
[_prepTime setFrame:noFrame];
prepTimeHeight = 0;

But the height of the UILabel still remains,

The I tried with:

[_prepTime removeFromSuperView];

With this one the UILabel gets removed but the interface changes since it has constraints and by removing the UILabel I destroy the layout.

Is there any method to remove the UILabel from the view even if it has constraints?

Upvotes: 0

Views: 655

Answers (2)

SeNeO
SeNeO

Reputation: 417

When using layout constraint it's not a good idea to edit the frame of your element. Instead you should add a IBOutlet property for your NSLayoutConstraint and link it to the height constraint of your label in your storyboard, then edit the constant value of the NSLayoutConstraint.

Someting like that in your viewcontroller @implementation:

@property IBoutlet NSLayoutConstraint *myLabelHeightConstraint;

and later when you want to hide your label :

self.myLabelHeightConstraint.constant = 0;
[self.view layoutIfNeeded];

Upvotes: 0

abhishekkharwar
abhishekkharwar

Reputation: 3529

You can set hidden if you don't want to affect all other subviews.

Upvotes: 2

Related Questions