views:

514

answers:

2

I have a UIViewController (named VC) that inherits from UITableViewDelegate and UIScrollViewDelegate. The previous UIViewController loads VC like this:

[self.view addSubview:VC.view];

which means viewWillAppear doesn't fire. I can add that method just after the above line:

[VC viewWillAppear];

but then it will fire before cellForRowAtIndexPath, which results in an empty tableview reference when I try to scroll.

I would like to scroll to a particular row in the table on load of VC. But because I don't know when the tableview's cellForRowAtIndexPath has completed (lack of viewWillAppear), I don't have any place to put the scroll code. I already keep a reference to the tableview and can use it for scrolling. But where can I place the scroll code?

A: 

Do you mean that your UIViewController conforms to the UITableViewDelegate and UIScrollViewDelegate protocols rather than 'inherits'?

You could invoke [VC viewWillAppear:] directly from your parent view controller. If the view handled by VC is always a sub-view of another view controller's view then do you really need a full UIViewController instance to back your UITableView? You could just provide a delegate and datasource implementation for the table view.

You could then instantiate your delegate and datasource either in the NIB that defines the table view (by adding an object in Interface Builder) or in the viewDidLoad method of the view controller that is currently the parent to VC.

teabot
Yes - "conforms". VC has an associated NIB so it needs to be a ViewController. I see what you mean about having the NIB instantiate the tableview delegate but then again, where does the scrollTo code go?
4thSpace
When/where does the parent VC call: [self.view addSubview:VC.view];
teabot
A: 


Surely when the new view controller's view is added and becomes visible, it will call the viewDidAppear rather than the viewWillAppear. I'd stick the scroll code in there.

If that still doesn't work then try a delay in your init method. Something like this:

[self performSelector:@selector(myScrollingFunction) withObject:nil afterDelay:2.0];

You could play around with the delay time to get something that suits, although your view controller's view may not always appear after the same amount of time.

imnk