Search code examples
objective-ciosuiscrollviewresizefill

iOS/Objective-C: Creating a UIScrollView which fills screen and reorients


I'm trying to achieve the simplest thing - creating a UIScrollView which fills (and exactly fits) the application frame (i.e. screen minus status bar height) regardless of device orientation.

This is proving very challenging though - the scroll view seems reluctant to resize correctly in landscape view, and I'm not sure why.

I decided to forget about using the application frame and simply attempt to fill the screen, ignoring status bar height, yet even this hasn't been possible.

You can see the approach I'm using below. Would anyone be kind enough to demonstrate how to do this correctly? I seem to permanently run into issues with sizing objects correctly, especially when attempting to fill the iPhone/iPad screen entirely.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    CGFloat viewedWidth, viewedHeight;
    const CGSize dim = [UIScreen mainScreen].bounds.size;
    if (UIInterfaceOrientationIsPortrait([UIDevice currentDevice].orientation)) {
        viewedWidth = dim.width;
        viewedHeight = dim.height;
    } else {
        viewedWidth = dim.height;
        viewedHeight = dim.width;
    }
    [self.scrollView setFrame:CGRectMake(0.0f, 0.0f, viewedWidth, viewedHeight)];
}

-(void)viewDidLoad {
    [self.view setFrame:[UIScreen mainScreen].bounds];
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,1,1)];
    [self.scrollView setDelegate:self];        
    [self.view addSubview:self.scrollView];
    [self.scrollView setContentSize:sizeManager.canvasSize];
    [self didRotateFromInterfaceOrientation:UIInterfaceOrientationPortrait]; // NOTE: orientation passed is not used, dummy
}

Your advice is most welcome, many thanks.


Solution

  • I would avoid trying to determine the size yourself; just let iOS do the work for you:

    - (void)viewDidLoad {
        UIScrollView *sv = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        sv.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [self.view addSubview:sv];
        [sv release];
    }
    

    This will ensure that the scroll view will always be resized along with its container view.