简体   繁体   中英

Resizing UIImageViews With Custom UIView with .xib File and AutoLayout

Here's the situation: I have a VC that has a Custom UIView inside it. This Custom UIView has an .xib file, which contains 2 UIImageViews. I'm trying to get those 2 UIImageViews to scale to same size across different screen size by using AutoLayout. However, when I launch my app the images in my Custom UIView go out of bounds of the Custom UIView's super View (which is the VC) container size. Please, help. Here are some pictures to explain the issue in better detail.

My code in Custom UIView: @implementation CustomTwoImagesSelectedUIView

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
        if (self) {
            [self load];
        }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
        if (self) {
            [self load];
        }
    return self;
}

- (void)load {
    [[NSBundle mainBundle] loadNibNamed:@"CustomTwoImagesSelectedUIView" owner:self options:nil];
    self.lastImageView.layer.cornerRadius = 5.0f;
    self.lastImageView.clipsToBounds = YES;
    self.secondToLastImageView.layer.cornerRadius = 5.0f;
    self.secondToLastImageView.clipsToBounds = YES;   
    [self addSubview:self.twoImagesSelectedView];
}

You have set the cliptobounds property of the imageviews but the bound of imageviews itself is not set properly I guess. You need to carefully set layout constraints in the .xib file for imageviews. Also. When you add the customImageViews to some view controller, or superview. You also need to set the layout constraints for customImageViews with respect to its superview.

I have try AutoLayout in the custom UIView, but it can not work too. I think it is a bug from Xcode, and I finally found this article: Create an IBDesignable UIView subclass with code from an XIB file in Xcode 6

In the article, I found it use autoresizingMask instead of AutoLayout. It is a good way to fix the UI display problem. I hope it can helps you.

- (void)load {
    [[NSBundle mainBundle] loadNibNamed:@"CustomTwoImagesSelectedUIView" owner:self options:nil];
    self.lastImageView.layer.cornerRadius = 5.0f;
    self.lastImageView.clipsToBounds = YES;
    self.secondToLastImageView.layer.cornerRadius = 5.0f;
    self.secondToLastImageView.clipsToBounds = YES;   
    [self addSubview:self.twoImagesSelectedView];

    self.twoImagesSelectedView.frame = self.bounds;
    self.twoImagesSelectedView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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