Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Autolayout to center three objects

I have a view that contains three labels.

The first label is placed at the very top. The third label is placed 50px from the bottom.

What I am trying to do is always place the second label in the center of those two using autolayout, but I can't figure how to do it.

The problem is that the second label isn't at the view's center.

I tried setting two vertical spacing constrains to less or equal to the initial value, but it did not work.

It is possible to do that only using autolayout? I thought about adding another view, but that does not look like a good solution..

Thank you.

like image 519
Marcelo Avatar asked Nov 12 '22 09:11

Marcelo


1 Answers

I don't think you can do this with auto layout; but it's trivial to override layoutSubviews (or viewDidLayoutSubviews if you're not using a UIView subclass) to center label 2 between label 1 and label 3 (just be sure to call [super layoutSubviews] first).

EDIT: Here's some sample code.

- (void)layoutSubviews {
    [super layoutSubviews];

    _label2.center = CGPointMake(_label2.center.x, (CGRectGetMaxY(_label1.frame) + CGRectGetMinY(_label3.frame)) / 2);
}
like image 169
fumoboy007 Avatar answered Nov 15 '22 06:11

fumoboy007