iPad Development 101 – viewWillAppear… gotcha!

Every so often when your programming with in various different languages you will come across what’s known as a “gotcha!”. These are the subtleties and sometimes undocumented (or hard to find) tricks to getting your code fully functional or working around a bug. These tricks can be differences in hardware/software, SDK/API or browsers.

When working with the iPhone SDK (3.2) I discovered that the viewWillAppear method is not called by default when you load a subview, this post will explain one possible workaround for the issue.

For example:

We are using an action to load the subview when a button is clicked, the action looks something like this:

(IBAction) loadMySubview:(id)sender{
	// Clear the active views
	[self clearView];
	// Add the subview
	[self.view insertSubview:mysubviewViewController.view atIndex:0];
}

This code works just fine to load the subview, but you will notice if you want to use the viewWillAppear method in your view controller you will need to tell your action that you want to run the viewWillApprear using the following line.

[mysubviewViewController viewWillAppear:YES];

Note that this line should come after your subview is added.

The action should look something like this:

(IBAction) loadMySubview:(id)sender{
	// Clear the active views
	[self clearView];
	// Add the subview
	[self.view insertSubview:mysubviewViewController.view atIndex:0];
	// Initiate the viewWillAppear method
	[mysubviewViewController viewWillAppear:YES];
}

Now in your view controller .m file you can add your viewWillAppear method and it will run each time the view is loaded:

(void)viewWillAppear:(BOOL)animated {
	// Do Stuff 
}

This can be useful for resetting the position of a UIScrollView or invoking other transformations / logic when your view is called.

Add a comment

Comment feed
The better to greet you with
No one will ever see this
Your pride and joy
The reason this comment form exists

The crew behind ASOT

We're a team of interactive, software, and business intelligence experts skilled in the design, construction, and management of online enterprise systems.

Visit The Jonah Group site

Get in touch with us