PDA

View Full Version : Reusing viewcontroller in Pagecontrol example




mrl72
Jan 30, 2011, 09:18 AM
I have implemented the lazy load view method from Apple's Pagecontrol sample project in order to create views that are lazy-loaded at run-time as the user flips through each page. Everything works great except now I want to re-use the controllers for another method in my app so that I can share the controllers and views rather than create new ones. The idea is that the user will touch a menu button which shows a particular image gallery using the views and then by selecting another menu button will display and load a new gallery but re-use the controllers. In my code I am doing the following:


// view controllers are created lazily
// in the meantime, load the array with placeholders which will be replaced on demand as we flip the page
-(void)initViewControllers {

NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < kNumberOfPages; i++)
{
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];
}


Then before I call my separate methods I am doing:


//Clear and init the controllers array
[viewControllers removeAllObjects];
[self initViewControllers];


And then in each method:


// replace the placeholder if necessary
MyViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null])
{
controller = [[MyViewController alloc] init];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}


// add the controller's view to the scroll view
if (controller.view.superview == nil)
{
CGRect frame = scrollView.frame;
frame.origin.x = (frame.size.width) * page;
frame.origin.y = 0;

controller.view.frame = frame;
[scrollView addSubview:controller.view];

}


But what's happening is if I call my second method it's displaying the views on top of the views that were displayed in my previous method. What I want to do is ensure that before the next method is called all views and its content is destroyed/removed before adding the views again. Can anyone suggest how to do this? I have even tried assigning tags before I add each view but this did not seem to work either.

Cheers.