Reputation: 59506
I created a WatchKit app with a Page-Based Interface.
There are 3 pages and each one is connected to my InterfaceController.swift class (which extends WKInterfaceController).
My question: inside InterfaceController.swift how can I detect the page number of the current view?
Upvotes: 4
Views: 2568
Reputation: 2529
It can be achieved this way,
Present InterfaceController in pageNavigation with Appropriate Context Values,
[self presentControllerWithNames:@[@"TestInterfaceController",@"TestInterfaceController",@"TestInterfaceController"] contexts:@[@"Page 1",@"Page 2",@"Page 3"]];
Then create a NSString property to track page and label to display it,
@property (nonatomic, strong) NSString *currentContext;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *pageLabel;
In awakeWithContext assign it to NSString property,
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
NSLog(@"%@",context);
self.currentContext = context;
}
Display it on willActive,
- (void)willActivate {
// This method is called when watch view controller is about to be visible to user
[super willActivate];
NSLog(@"%@ willActivate",self.currentContext);
[self.pageLabel setText:self.currentContext];
}
You can also detect when page didDeactivate,
- (void)didDeactivate {
// This method is called when watch view controller is no longer visible
[super didDeactivate];
NSLog(@"%@ didDeactivate",self.currentContext);
}
Edit : If page navigations are configured using Storyboard Segue then override this method in Source IntefaceController from where you created model segue to destination controller to provide contexts,
- (NSArray *)contextsForSegueWithIdentifier:(NSString *)segueIdentifier {
NSArray *contexts = nil;
if ([segueIdentifier isEqualToString:@"MyPageNavigation"]) {
contexts = @[@"Page 1",@"Page 2",@"Page 3"];
}
return contexts;
}
Upvotes: 0
Reputation: 510
If you use
func presentControllerWithNames(_ names: [AnyObject],
contexts contexts: [AnyObject]?)
You just have to pass the number of the page in the context, so you can store it, and retrieve it later on. This is the non storyboard way.
If you use storyboard, it is the same, you just have to use the other method
func contextsForSegueWithIdentifier(_:inTable:rowIndex:)
And pass your page index in the context of each controller
Upvotes: 2