[英]How to properly add an UIImageView inside an UIStackView
My UIImageView is loaded with a picture with a high resolution. 我的UIImageView加载了一个高分辨率的图片。 When I add the UIImageView to the UIStackView, the stack view will grow up to 1900x1200 dimension. 当我将UIImageView添加到UIStackView时,堆栈视图将增长到1900x1200维度。 The UIImageView contentMode is set to Aspect Fill. UIImageView contentMode设置为Aspect Fill。
What can I do so that the image remains with its current dimension (130x130) after adding it to the stack view ? 在将图像添加到堆栈视图后,我该怎么做才能使图像保持当前尺寸(130x130)?
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. 只需将高度和宽度约束添加到UIImageView,然后再将其放入堆栈视图中。 Make them both 130 and you should be good to go. 让他们都130,你应该很高兴去。
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
. 我的UIImageView
没有直接添加到UIStackView
,而是包含在普通的UIView
。 This way I can avoid interfering directly with any constraints that UIStackView
creates for each added subview. 这样我就可以避免直接干扰UIStackView
为每个添加的子视图创建的任何约束。
Example using PureLayout: 使用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
set 组
clipToBounds = true
You can achieve this by Interface builder by checking the option for Image view or you can add code as 您可以通过选中“图像”视图的选项,通过“界面”构建器实现此目的,也可以将代码添加为
imageView.clipToBounds = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.