Page number in Page-Based Interface with WatchKit (Watch)?

怎甘沉沦 提交于 2019-12-07 10:08:37

问题


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?


回答1:


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




回答2:


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;
}


来源:https://stackoverflow.com/questions/27579555/page-number-in-page-based-interface-with-watchkit-watch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!