如何在UIStackView中正确添加UIImageView

问题描述 投票:12回答:3

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

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

ios uiimageview autolayout uistackview
3个回答
19
投票

我希望你现在已经回答了你的问题,但如果不是,你去吧:

只需将高度和宽度约束添加到UIImageView,然后再将其放入堆栈视图中。让他们都130,你应该很高兴去。


3
投票

我能够通过图像视图的设置宽高比来克服这个问题。我的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

0
投票

clipToBounds = true

您可以通过选中“图像”视图的选项,通过“界面”构建器实现此目的,也可以将代码添加为

imageView.clipToBounds = true
© www.soinside.com 2019 - 2024. All rights reserved.