Programmatically create a page based navigation

Hello guys, I need to create a page based navigation where the number of pages are dynamic and I can know the number only at runtime.

Suppose you have a "template" view controller; when I know I've 6 pages to display I would to allocate the same template view controller six times and setup it in my page based controller.

From what I've read this seems not be possible at this time. Is it true?

Accepted Answer

Fortunately you're wrong. 😝

In order to create a customized navigation based app you have to:


1. Create a base Interface Controller and set its Identifier (for example "page")


2. Reload Root Controllers in parent Interface Controller:

- (void)willActivate {
    // This method is called when watch view controller is about to be visible to user
    [super willActivate];

    // create pages controllers
    NSMutableArray *controllersNames = [NSMutableArray arrayWithCapacity:pageCount];
    NSMutableArray *controllersContexts = [NSMutableArray arrayWithCapacity:pageCount];
    if (pageCount) {
        for (uint8_t i = 0; i < pageCount; i++) {
            [controllersNames addObject:@"page"];
            [controllersContexts addObject:@[self, @(i)]];
        }
    }
    else {
        // no pages controller
        [controllersNames addObject:@"nopage"];
        [controllersContexts addObject:@[self, @(0)]];
    }

    // reload base controller
    [WKInterfaceController reloadRootControllersWithNames:controllersNames contexts:controllersContexts];
}

You will pass page number as Context to identify your pages.


3. Then you can easily get page number from every loaded page in base Interface Controller's awakeWithContext:

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    // set page ID
    pageID = [[context objectAtIndex:1] unsignedIntValue];
}

Great 🙂

However using reloadRootControllersWithNames methods the entire application hierarchy is reloaded automatically and I lost the page where I came from.

Suppose I've an initial page with a button; this button should push to this page-based interface.
Is it possible too?


UPDATE

I've tried using presentControllerWithNames and it works fine, but with a push instead of a present it should work better. However I cannot find any method like this.

I think it's not possible. The only way creating a page based app seems to be by using reloadRootControllersWithNames and this will destroy your current navigation stack.

By pushing your base controller you will preserve your current root controller.

So you should use presentControllerWithNames to create a new navigation stack with your base controller as Root.

Programmatically create a page based navigation
 
 
Q