簡體   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