Search code examples
objective-ciosuiviewcontrolleruiscrollviewcontentoffset

Setting UIScrollView's Position from another ViewController


I am trying to set the position of a UIScrollView by using contentOffset as such:

- (void) navigateToTableViewPosition:(CGPoint)contentOffset {
    NSLog(@"Position set method gets called...");
    NSLog(@"%@", NSStringFromCGPoint(contentOffset));
    [mainScrollView setContentOffset:contentOffset animated:YES];
}

I call this method from another view controller before I dismiss it, and everything checks out. I pass the argument correctly, and the method gets called (checked it with NSLog), but the scroll view does not move...

What is funny is that when I call this method from the view controller, in which it is located, it works fine. Only when I call it from another view controller, it stops working.

Just for future reference, here is the calling method:

MainViewController *mainView = [[MainViewController alloc] init];
[mainView navigateToTableViewPosition:contentOffset];

Content offset is a CGPoint I set beforehand. It doesn't matter here; besides, it gets passed correctly anyways.


Solution

  • Try this, You have to send notification from other viewcontroller when you want to change ..

        [[NSNotificationCenter defaultCenter] postNotificationName:@"changepostion"        object:NSStringFromCGPoint(CGPointMake(contentOffset.x, contentOffset.y))];
    

    in mainviewcontroller

      -(void)viewDidLoad
    
      {
         [[NSNotificationCenter defaultCenter] removeObserver:self];
             [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(navigateToTableViewPosition:) name:@"changepostion" object:nil];
    
      }
    
    - (void) navigateToTableViewPosition:(NSNotification *)notification
      {
            contentOffset =CGPointFromString([notification object]);
    
       NSLog(@"Position set method gets called...");
       NSLog(@"%@", NSStringFromCGPoint(contentOffset));
        [mainScrollView setContentOffset:contentOffset animated:YES];
     }