繁体   English   中英

如何在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM