1

How to center vertically two UILabel (dynamic heights) inside a view, like this with Label1 (2 lines, truncated) and Label2 (1 line, truncated):

+------------------------------------------+
|                                          |
|                                          |
|Label1 Label1 Label1 Label1 Label1 Label1 |
|Label1 Label1 Label1 Label1 Label1 ...    |
|Label2 Label2 Label2 Label2 Label2 ...    |
|                                          |
|                                          |
+------------------------------------------|

I guess this is not possible with a single UILabel and a NSAttributedString (to truncate one part on 2 lines, and another part on 1 line).

keo
  • 33
  • 3

2 Answers2

1

If you are using auto layout, you can embed the two labels in a parent UIView, and then use a constraint to vertically center the parent UIView in its superview.

Greg
  • 33,450
  • 15
  • 93
  • 100
  • 1
    Both UILabel are multiline and the height is not static, so I think your solution is not applicable. – keo Oct 01 '13 at 22:36
  • 1
    @keo, AutoLayout is designed for this exact sort of situation. When views are set to use their intrinsic content size, they will adjust as the content changes and cause the layout to recalculate. – Brian Nickel Oct 01 '13 at 22:38
  • @hasan Thanks, but I think AutoLayout is a better solution for this purpose. – keo Oct 01 '13 at 23:05
  • And make the parent view expand dynamically; which can be achieved by connecting edges of subviews to parent rigidly. More Details: http://stackoverflow.com/a/19194592/1586606 – Ammar Mujeeb May 16 '16 at 13:30
0

You can get labels frame in view did appear and replace them on the screen again. I tried that before and it worked. may you also need to call setNeedsDisplay.

- (void)viewDidAppear:(BOOL)animated {

   float heights = lbl1.frame.size.height + lbl2.frame.size.height;
   lbl1.frame = CGRectMake( lbl1.frame.origin.x, screenheight/2 - heights/2, lbl1.frame.size.width, lbl1.frame.size.height );
   lbl2.frame = CGRectMake( lbl2.frame.origin.x, screenheight/2 - heights/2 + lbl1.frame.size.height, lbl2.frame.size.width, lbl2.frame.size.height );
  [lbl1 setNeedsDisplay];
  [lbl2 setNeedsDisplay];
}
hasan
  • 23,815
  • 10
  • 63
  • 101