Center a UIImageView and a UILabel together in a U

2019-08-07 05:50发布

问题:

If I declare a UILabel and a UIImageView of different sizes can I then center them in a UIView with 10.0points between the two horizontally?

Thanks!

回答1:

Yes you can. Basically what you need is appropiate constraints. You can add constraints from code or in stoaryboard

Code example:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeCenterX multiplier:1 constant:5];
[view addConstraint:constraint];

NSLayoutConstraint Documentation

Auto Layout Tutorial

Adaptive Layout Tutorial



回答2:

This can be accomplished using AutoLayout. You cans set the right margin of the label to be 5 points to the left of the superview CenterX and the imageview left margin to be 5 points to the right of the superview CenterX.