简体   繁体   中英

Vertically center subview using Auto-Layout

I'm trying to figure out how to center vertically a view using Auto-Layout. I'm new to this technology so it makes me some problems... This is my controller in Interface Builder: 在此处输入图片说明

The gray part is the superview and it contains a custom view (the yellow one) and a label (the red one); the yellow view is fixed at the bottom of the superview and it has fixe height and width. The red view has fixed width and height, too.

My goal is to center vertically my red view in the visible part of the gray view, whose visible height is superview.height - yellowView.height . How can I do that?
Thank you so much!

The easiest way to do it, would be to make the gray view a subview of the main view too, and then you can just give the label a centerY constraint in IB or in code. If you can't so that for some reason, you can change the constant value of a centerY constraint in code, giving it a value of 1/2 the height of the yellow view. Give the label a centerY constraint in IB and make an IBOutlet to it (I call it centerCon in my example). The fixed height of my yellow view was 200.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.centerCon.constant = 100;
}

这里最简单的解决方案之一将是这样的:

redView.center = CGPointMake(superview.width/2, (superview.height - yellowView.height)/2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM