以编程方式使用 AutoLayout 将多行 UILabel 的第一行与 UIImage 对齐 ( Objective-C )

Align first line of multiple lines UILabel with UIImage using AutoLayout programmatically ( Objective-C )

我正在尝试将多行 UILabel 与 UIImage 对齐。问题是:我想将此标签的第一行与图像水平对齐。

我尝试了什么:

1 - 将图像与整个 UILabel 对齐,所以基本上我还是想把图像拿起来。

[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[image(width)]-8-[multiLinesLabel]|" options:NSLayoutFormatAlignAllCenterY metrics:metrics views:views]];

2 - 所以我尝试了这个,但是图像太高了。

[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[image(width)]-8-[multiLinesLabel]|" options:NSLayoutFormatAlignAllTop metrics:metrics views:views]];

有人有想法吗?

提前致谢

编辑:我终于成功了:

[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[image(width)]-8-[multiLinesLabel]|" options:kNilOptions metrics:metrics views:views]];

[containerView addConstraint:[NSLayoutConstraint
                                      constraintWithItem:image
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:multiLinesLabel
                                      attribute:NSLayoutAttributeTop
                                      multiplier:1.0
                                      constant:3.0]];

我并不为自己感到骄傲,这不是解决问题的干净方法,但它确实有效。如果有人考虑其他解决方案...

您可以添加具有相同字体和单个文本字符的单行虚拟标签。让它隐藏起来。定位它以与您的图像对齐,然后定位多行标签的上边缘以与虚拟标签对齐。