user443854
user443854

Reputation: 7473

How to reuse WKInterfaceTable in WatchKit

I chose page-based layout for my WatchKit app. Each page shows a table. I want to keep the layout of the table exactly the same across all pages. I will be feeding filtered data to each page at run time, so essentially pages will be identical, except the data will be different.

enter image description here

One way to achieve this is to manually create InterfaceController instance for each page in InterfaceBuilder, then populate with GUI elements and connect the outlets. The problem here is whenever I want to change something (say, move a label or add a button), I will have to apply that change consistently to every page.

Moreover, for each page I have to connect the outlets to table row controller, essentially repeating myself over and over again. Here's an illustration:

enter image description here

Is there a way to reuse a table?

I considered inheritance, but the documentation tells me not to subclass WKInterfaceTable. This also rules out creating a table programmatically.

Upvotes: 2

Views: 1268

Answers (2)

cnoon
cnoon

Reputation: 16663

You should create a single interface controller with the table and various row types. Then you want to create an architecture very similar to my answer here. You'll only have a single PageOneInterfaceController which should be named TableInterfaceController in this example with TableInterfaceIdentifier as the identifier. Then you would do the following:

MainInterfaceController.swift

func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    let context1 = "context 1 - for you to fill out"
    let context2 = "context 2 - for you to fill out"
    let context3 = "context 3 - for you to fill out"

    WKInterfaceController.reloadRootControllersWithNames(
        ["TableInterfaceIdentifier", "TableInterfaceIdentifier", "TableInterfaceIdentifier"], 
        contexts: [context1, context2, context3]
    )
}

This will reload the page set using the same interface controller that displays all the data in the respective context.

Upvotes: 2

bgilham
bgilham

Reputation: 5939

To accomplish this, provide the same WKInterfaceController in reloadRootControllersWithNames:contexts: multiple times, but provide a different context to each one.

Upvotes: 2

Related Questions