Udało mi się przezwyciężyć to przez współczynnik proporcji obrazu dla widoku obrazu. Mój UIImageView
nie jest bezpośrednio dodawany do UIStackView
, zamiast tego jest zawijany zwykłym UIView
. W ten sposób uniknę interferencji bezpośrednio z ograniczeniami, które tworzy dla każdego dodanego podglądu.
Przykład wykorzystania 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
Dodaj ograniczenia. Twoje pytanie jest zbyt szerokie ... – Wain
[self addConstraint: [NSLayoutConstraint constraintWithItem: atrybut myUIImageVIew: NSLayoutAttributeWidth relatedBy: NSLayoutRelationEqual toItem: nil atrybut: NSLayoutAttributeNotAnAttribute mnożnik: 1.f stałe: 130]]; [self addConstraint: [NSLayoutConstraint constraintWithItem: myUIImageVIew atrybut: NSLayoutAttributeHeight relatedBy: NSLayoutRelationEqual toItem: atrybut nil: mnożnik NSLayoutAttributeNotAnAttribute: 1.f stała: 130]]; – Loxx