AutoLayout setting UILabel height to zero

前端 未结 5 1527
暗喜
暗喜 2021-02-14 01:40

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 b

相关标签:
5条回答
  • 2021-02-14 02:19

    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];
    }
    
    0 讨论(0)
  • 2021-02-14 02:28

    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 (>=)

    0 讨论(0)
  • 2021-02-14 02:41

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

    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.

    0 讨论(0)
  • 2021-02-14 02:43

    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;
    }
    
    0 讨论(0)
  • 2021-02-14 02:43

    AutoLayout in this UIViewController can't satisfy all the constraints you have set, therefore it dismiss those on your UILabel, resulting in a compressed state. You should have a look at the other constraints in your UIViewController, and set the priority of the height contraint to a higher number.

    0 讨论(0)
提交回复
热议问题