API Development

How-To: Create an iPhone Navigation Group

A question that’s come up a bit in Q&A, chats, tweets, and e-mails I get from folks in the community is the question of how to create what in the native world would be called a NavigationController. It’s basically a single window container which has a built in title bar, and allows you to arrange windows in a navigable stack. In previous versions of the Titanium Mobile SDK, the only way to achieve this automatic window navigation was to use a tab group, but in our latest release that’s no longer the case. There’s an implementation of a Navigation Controller in the iPad Kitchen Sink, but I thought I would do a quick walkthrough of how to create a simple navigation group in your iPhone app.

Our first order of business is to create the initially viewable window of our application – we’ll also add a label that the user can touch to open a second window:

//Here's the first window...
var first = Ti.UI.createWindow({
  backgroundColor:"#fff",
  title:"My App"
});
var label = Ti.UI.createLabel({ text: "poke me to open the next window" });
first.add(label);

Next, we’ll create a NavigationGroup. This is an iPhone-only component that controls a stack of windows (reference doc) – we’ll pass it our first window to use as its initially viewable window:

//Here's the nav group that will hold them both...
var navGroup = Ti.UI.iPhone.createNavigationGroup({
window:first
});

Next, we’ll create a child window to push onto the stack:

//Here's a window we want to push onto the stack...
var second = Ti.UI.createWindow({
  background:"#fff",
  title:"Child Window"
});
second.add(Ti.UI.createLabel({text:"Here's the child"}));

When we want to open a sub-window on our navigation group, we pass the window we want to open as an argument to the NavigationGroup’s open method. Finishing up, we will add our nav group to a window that will serve as our application’s primary UI container:

//When the label on the first window receives a touch, open the second
label.addEventListener("click", function(e) {
  navGroup.open(second);
});

//This is the main window of the application
var main = Ti.UI.createWindow();
main.add(navGroup);
main.open();

When we’re finished, we’ll have a navigable stack of windows that give us a nice means of organizing some hierarchical data with some nifty built-in transitions:

Here’s the finished application, which you can drop in an app.js file and run yourself:

Hope that helps!