Search code examples
iosdynamicautolayoutsizetofit

Dynamic view changes (i.e. UILabel) with autoLayout


I need to create two UILabels which should be resized dynamically based on text size inside UITableViewCell. The first UILabel should grow (based on the text) to the left and always align 15 points to the right border. the second UILabel should (also grow dynamically to the left) and be aligned 7 points to the right of the first UILabel.

... [label 2]<--7p-->[label 1]<--15p-->|right cell border

  1. Can this be done only on the storyBoard (without code) ?
  2. I defined a horizontal constraints in the storyboard layout and sizeToFit: on the code. and found out that the horizontal constraints were overridden. Tried to change frames in the viewDidLoad: but not all were updated (performing selector with 0 delay - update all labels in all of the cells but created a one second delay.)

Please advise, Thanks Asaf


Solution

  • Question 1)

    Actually you can do that in code. but I think Interface Builder better in your case.

    I think you don't have to [sizeToFit:] in code.

    if you don't set the width constraints to your labels, I think there is warning in your storyboard.

    UIControls like UILabel, UIButton has intrinsic size because they have a text content. so you don't need to set the width constraint.

    but you have a two labels and you should let autolayout knows which label is more important when there is conflict between labels. - ex. if labels have long text, which label's text are shown without shortening(...).

    To do that, set the Hugging (or Compression) Priority in Interface Builder.

    Question 2)

    [viewDidLoad:] is not suitable for changing geometry things. View of UIViewController is added in view hierarchy after [viewWillAppear:]

    if you need more information, please let me know.