Asaf
Asaf

Reputation: 91

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

Upvotes: 2

Views: 294

Answers (2)

Keenle
Keenle

Reputation: 12200

You can achieve the result either in code or with StoryBoard auto-layout. Here are the steps for Storyboard auto-layout:

1. Ensure that you have cell with two labels and no auto-layout constraints(clear them if any)

2. Add constraints to Label 1:

TwoLabelsCell_Label1_Constraints

3. Add constraints to Label 2:

TwoLabelsCell_Label2_Constraints

Result:

TwoLabelsCell_Result

Remarks:

  • Manipulations with layout should be done by overriding updateViewConstraints in your view controller. Just do not forget to call [super updateViewConstraints].

  • No need to deal with sizeToFit: method in your case.

Upvotes: 1

soulpark
soulpark

Reputation: 96

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.

Upvotes: 1

Related Questions