Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollView Setting contentoffset in viewwillappear not working

I was wondering if it is possible to set contentoffset for uiscrollview in viewwillappear method.

-(void) viewWillAppear:(BOOL)animated{

    [self.scrollView setContentOffset:CGPointMake(320, 0) animated:YES];
    NSLog(@"CALLED");    
}

I can see viewwillappear is running but unfortunately it is not setting offset.

Thank you

like image 239
Asif Alamgir Avatar asked Sep 18 '14 14:09

Asif Alamgir


People also ask

What is UIScrollView in UIKit?

UIScrollView is the superclass of several UIKit classes, including UITableView and UITextView. A scroll view is a view with an origin that’s adjustable over the content view. It clips the content to its frame, which generally (but not necessarily) coincides with that of the application’s main window.

What is Scroll View in UITableView?

A view that allows the scrolling and zooming of its contained views. UIScrollView is the superclass of several UIKit classes, including UITableView and UITextView. A scroll view is a view with an origin that’s adjustable over the content view.

What is the difference between Scroll View and clip view?

It clips the content to its frame, which generally (but not necessarily) coincides with that of the application’s main window. A scroll view tracks the movements of fingers, and adjusts the origin accordingly.

How does the scroll view change the scale of the content?

As the user makes a pinch-in or pinch-out gesture, the scroll view adjusts the offset and the scale of the content. When the gesture ends, the object managing the content view should update subviews of the content as necessary.


2 Answers

you should call [super viewWillAppear:animated]; before attempting to set the offset.

However, it is possible you are trying to set the offset too early in the view lifecycle.

it might be good to override -(void)viewDidLayoutSubviews;, and set the offset there.

as your view's frames should all be set appropriately by that time. (remember to call super there too)

like image 111
Nick Avatar answered Sep 29 '22 12:09

Nick


I have an alternative option that should work better:

Instead of overriding viewDidLayoutSubviews, you can manually set the layout:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    view.layoutIfNeeded()
    // Do something here
}

This way you get a fresh layout that should match your expectation

like image 21
Antzi Avatar answered Sep 30 '22 12:09

Antzi