Search code examples
iosuiviewautoresizingmask

Scale a UIView automatically on orientation change to scale proportionaltely to fit in parent view


A UIImage view set to "Aspect Fit" will automatically dynamically scale it's image to fit within the current bounds of the UIUmageView, while maintaining the image's proportions. A UIView set to "Aspect Fit" does not seem to have this same effect on it's sub-views.

I have tried to set the parent view via code, with the code below, and tried several variations on the auto-resizing mask ( I am not using auto layout). Am I missing something obvious, or do I need to write a little code to compute the right scale for my sub-view based on the current size of the parent view?

[self.view setContentMode:UIViewContentModeScaleAspectFit];

Solution

  • I've been playing around with it. This is incomplete, just handles the portrait subview scaling, but works ok so far.

    if (self.view.bounds.size.width < self.view.bounds.size.height) {
        NSLog(@"view is portrait");
        if (_sview.frame.size.width < _sview.frame.size.height) {
            NSLog(@"subview is portrait");
            [UIView animateWithDuration:0.1
                             animations:^{
                                 _sview.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
                             }];
        } else {
            NSLog(@"subview is landscape");
        }
    } else {
        NSLog(@"landscape");
        if (_sview.frame.size.width < _sview.frame.size.height) {
            [UIView animateWithDuration:0.1
                             animations:^{
                                 _sview.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.65, 0.65);
                             }];
        } else {
            NSLog(@"subview is landscape");
        }
    
    }