Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoLayout setting UILabel height to zero

I have a UILabel for item description amongst other views, all laid out using constraints in Interface Builder - you can see all relevant constraints in the image below. The number of lines is also set to 0.

enter image description here

I haven't set the height constraint because I want the UILabel to resize based on the text it contains. Instead, what happens is right after

[self.view layoutIfNeeded];

is called, the height of the UILabel gets set to 0. Even if I don't set other text to the UILabel, it has a default value of Item description set in Interface Builder.

The item title label above is set the same way, but that one doesn't get squashed to 0, so I'm a bit confused.

Anyone had any experience with such behaviour?

like image 665
artooras Avatar asked Aug 28 '15 13:08

artooras


4 Answers

I managed to solve it by setting the UILabel's vertical compression resistance priority to 1000 (default 750) in Interface Builder.

enter image description here

Since my views are embedded in another view, and the parent view's bottom is dependent on the bottom of the lowest child view, I only speculate that the UILabel without a height constraint was getting squeezed in the process of laying out the views. Probably playing with priorities of other constraints somewhere down the chain would have yielded the same result, but I wasn't able to do it successfully. The solution above, however, worked, which is good enough in my case.

Hope this helps someone.

like image 146
artooras Avatar answered Oct 06 '22 16:10

artooras


I think you need to set 5 constraints on your label :

  • Leading space to superview
  • Trailing space to superview
  • Vertical space to "Item"
  • Vertical space to "Name"
  • Height

Then add an IBOutlet in your controller on the constraint height (let's say labelHeight).

So in your viewDidLoad you will be able to set this constraint value:

@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelHeight;


- (void) viewDidLoad{
   [self.label sizeToFit];
   labelHeight.constant = self.label.frame.size.height;
}
like image 39
Y.Bonafons Avatar answered Oct 06 '22 17:10

Y.Bonafons


Set 3 constraint

1.Leading space to superview

2.Trailing space to superview

3.Top space to superview

then

@property (nonatomic, strong) IBOutlet UILabel *lbl;

- (void) viewDidLoad{
   [self.lbl sizeToFit];
}
like image 38
iPhone Avatar answered Oct 06 '22 18:10

iPhone


ctrl drag from the label to itself > select height > set the constant of the height to 0 and change equal (==) to greater than or equeal (>=)

like image 36
Rick van der Linde Avatar answered Oct 06 '22 18:10

Rick van der Linde