我想将我的 UIImageView 和 UILabel 居中,如下图所示。我使用了一个容器来包含UIImageView和UILabel,但是容器不适合UIImageView和UILabel的宽度,所以我需要设置容器的宽度。有什么方法可以解决问题而不设置宽度或计算视图的宽度?这是图片:

我想将我的 UIImageView 和 UILabel 居中,如下图所示。我使用了一个容器来包含UIImageView和UILabel,但是容器不适合UIImageView和UILabel的宽度,所以我需要设置容器的宽度。有什么方法可以解决问题而不设置宽度或计算视图的宽度?这是图片:

有四种视图在起作用:
视图位于以下层次结构中:
我假设外部视图从其他约束中获取其宽度和高度。
我从您提供的图像中看到的图像高于标签,请记住以下约束可以实现您想要的:
[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];
感谢@abdullah。他清除了我的思绪。我忘了“将标签的右边缘固定到容器视图”,所以containerView'width变成了 0。
这是快速版本:
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)