I want to center my UIImageView and UILabel like the pic below. I used a container to contain UIImageView and UILabel,but the container does not suit the width of UIImageView and UILabel.So I need to set the width of the container.Is there any method to solve the problem without set the width or calculate the view's width? Here's the picture:
iOS how to center two view via PureLayout
7.8k Views Asked by Kevin Hawk At
3
There are 3 best solutions below
0

Here's the swift version:
button.autoPinEdge(toSuperviewEdge: .left, withInset: 15)
button.autoPinEdge(toSuperviewEdge: .right, withInset: 15)
button.autoSetDimension(.height, toSize: 46)
button.autoAlignAxis(.vertical, toSameAxisOf: contentView)
containerView.autoAlignAxis(toSuperviewAxis: .horizontal)
containerView.autoAlignAxis(toSuperviewAxis: .vertical)
iconImageView.autoPinEdge(.left, to: .left, of: containerView)
iconImageView.autoAlignAxis(toSuperviewAxis: .horizontal)
label.autoPinEdge(.right, to: .right, of: containerView)
label.autoAlignAxis(toSuperviewAxis: .horizontal)
label.autoPinEdge(.left, to: .right, of: iconImageView, withOffset: 10.0)
0

[self.button autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
[self.button autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
[self.button autoSetDimension:ALDimensionHeight toSize:46];
[self.button autoAlignAxis:ALAxisVertical toSameAxisOfView:self.contentView];
[self.containerView autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
[self.containerView autoAlignAxisToSuperviewAxis:ALAxisVertical];
[self.iconImageView autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.containerView];
[self.iconImageView autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
[self.label autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.containerView];
[self.label autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
[self.label autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.iconImageView withOffset:10];
Thanks to @abdullah. He cleared my mind. I forgot to "Pin right edge of label to container view", so the containerView
's width
became 0.
There are four view in action:
The views are in following hierarchy:
I assume that the outer view gets its width and height from other constraints.
What I see from the image you provided that image is taller than label, keeping that in mind following constrains could achieve what you want: