How to properly add an UIImageView inside an UIStackView
I was able to overcome this by settings aspect ratio for image view. My UIImageView
is not directly added to UIStackView
, instead wrapped in plain UIView
. This way I can avoid interfering directly with any constraints that UIStackView
creates for each added subview.
Example using 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
I hope you got your question answered by now, but if not here you go:
Simply add a height and width constraint to your UIImageView before putting it in your stack view. Make them both 130 and you should be good to go.