如何在 UIStackView 中正确添加 UIImageView

How to properly add an UIImageView inside an UIStackView

我的 UIImageView 加载了一张高分辨率的图片。当我将 UIImageView 添加到 UIStackView 时,堆栈视图将增长到 1900x1200 尺寸。 UIImageView contentMode 设置为 Aspect Fill。

我该怎么做才能使图像在添加到堆栈视图后保持其当前尺寸 (130x130)?

我希望你的问题现在已经得到解答,但如果还没有,请继续:

在将其放入堆栈视图之前,只需向 UIImageView 添加高度和宽度约束。把它们都设为 130,你就可以开始了。

我能够通过设置图像视图的宽高比来克服这个问题。我的 UIImageView 没有直接添加到 UIStackView,而是包裹在普通的 UIView 中。这样我就可以避免直接干扰 UIStackView 为每个添加的子视图创建的任何约束。

使用 PureLayout 的示例:

#import <math.h>
#import <float.h>

@interface StackImageView : UIView

@property (nonatomic) UIImageView *imageView;
@property (nonatomic) NSLayoutConstraint *aspectFitConstraint;

@end

@implementation StackImageView

// skip initialization for sanity
// - (instancetype)initWithFrame:...

- (void)setup {
    self.imageView = [[UIImageView alloc] initForAutoLayout];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;

    [self addSubview:self.imageView];

    // pin image view to superview edges
    [self.imageView autoPinEdgesToSuperviewEdges];
}

- (void)setImage:(UIImage *)image {
    CGSize size = image.size;
    CGFloat aspectRatio = 0;

    // update image
    self.imageView.image = image;

    if(fabs(size.height) >= FLT_EPSILON) {
        aspectRatio = size.width / size.height;
    }

    // Remove previously set constraint
    if(self.aspectFitConstraint) {
        [self.imageView removeConstraint:self.aspectFitConstraint];
        self.aspectFitConstraint = nil;
    }

    // Using PureLayout library
    // you may achieve the same using NSLayoutConstraint
    // by setting width-to-height constraint with
    // calculated aspect ratio as multiplier value
    self.aspectFitConstraint =
    [self.imageView autoMatchDimension:ALDimensionWidth  
                           toDimension:ALDimensionHeight 
                                ofView:self.imageView
                        withMultiplier:aspectRatio 
                              relation:NSLayoutRelationEqual];
}

@end

设置

clipToBounds = true

您可以通过界面生成器通过选中图像视图或 您可以将代码添加为

imageView.clipToBounds = true