UIScrollView scrolling automatically by 64 points

Viewed 1367

I'm adding a UIScrollView to a UIViewControllers view. For some reason, between adding the scroll view to the view and it getting displayed, the contentOffset is set to {0, -64}, 64 being the status bar's 20 plus the navigation bar's 44 points (I guess). Below is some code that reproduces the issue, and an image.

How do I prevent iOS from setting the contentOffset?


- (void)viewDidLoad
{
    [super viewDidLoad];

    _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 100, 100, 100)];
    _scroll.backgroundColor = [UIColor greenColor];
    _scroll.delegate = self;

    UIView *red = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    red.backgroundColor = [UIColor redColor];
    [_scroll addSubview:red];

    [self.view addSubview:_scroll];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // outputs {0, -64}
    NSLog(@"%@", NSStringFromCGPoint(_scroll.contentOffset));
}

Screenshot

2 Answers

Set automaticallyAdjustsScrollViewInsets on your view controller to NO, otherwise it'll adjust insets on the first subview of it's root view that happens to be of UIScrollView class.

More on this in iOS 7 Transition Guide.

For iOS 11+, set UIScrollView's contentInsetAdjustmentBehavior = .never to prevent the system from adjusting contentOffset automatically when it's being added to another view

Related