在启动循环中基于页面 "reloadRootControllersWithNames:"?

Page Based "reloadRootControllersWithNames:" on launch loop?

- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
    [WKInterfaceController reloadRootControllersWithNames:@[@"pageOne", @"pageTwo"] contexts:nil];
}

遵循 Apple 的指导方针

Call this method to reload the pages in your app’s page-based interface. At launch time, you use this method to customize the set of pages you want displayed.

在启动时,只会导致循环。每次重新加载调用 awakeWithContext 或将一次又一次地激活或初始化。

有没有更好的方法来在启动时重新加载基于页面的应用程序并发生循环?

这是 WatchKit 应用程序的常见问题,因为我们不再有 UIApplicationDelegate 来处理此类设置。一个好的方法是按如下方式构建代码:

  • MainInterfaceController(故事板中的主要 link 点在这里)
  • PageOneInterfaceController - 您在页面集中显示的第一个界面
  • PageTwoInterfaceController - 您在页面集中的第二个界面

MainInterfaceController 永远不会真正显示出来。根据 MainInterfaceController.awakeWithContent() 中配套 iOS 应用程序的缓存状态,您将始终启动到一组不同的界面控制器。这样,您使用 MainInterfaceController 的方式类似于我们在 iOS 中使用 UIApplicationDelegate 来设置 window 和根视图控制器。

我在一个应用程序中使用了这种方法,该应用程序有许多不同的页面集可供选择并且效果很好。

真的很容易解决,而且不需要多个页面控制器——只需使用一次

创建一个 class 变量(不是实例变量)并将其用作您的标志以确保您对 reloadRootControllers 的调用只被调用一次。

static NSString* hasLaunchedIfNotNullString = NULL;

- (void)awakeWithContext:(id)context
{
    if(hasLaunchedIfNotNullString == NULL)
    {
        //START Code which gets executed once
        hasLaunchedIfNotNullString = @"";

        ...
        [WKInterfaceController reloadRootControllersWithNames:YOUR_ARRAY contexts:CONTEXTS];
        // END code which gets executed once
    }
}

这就是 awakeWithContext: 存在的原因。首次启动您的应用程序时,初始控制器将 nil 作为 context 传递。但是如果你reloadRootControllersWithNames:contexts:,你就有机会传递一个自定义上下文实例,从而区分启动模式。

调用WKInterfaceController.reloadRootControllers 导致唤醒函数被第二次调用。这是我使用的解决方案——它直接、紧凑,并且消除了递归循环。此示例有两个基于页面的视图,称为 mainControls 和 nowPlaying,它们配置了上下文。请注意,这里的关键是使用空字符串上下文配置 mainControls 视图控制器,然后检查该上下文,如果由于 WKInterfaceController.reloadRootControllers 语句将上下文配置为 "" 而再次调用它,则 returns .请注意,第一次 awake 运行时,主视图控制器的上下文将为 nil。另请注意,第二个上下文是特定于我的实现的实现细节 - 这可以是您想要传递给第二个视图控制器的任何对象。

override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    if let _ = context as? String {
        print("already configured!")
        return
    }
    print("configuring...")
    WKInterfaceController.reloadRootControllers(withNames: ["mainControls", "nowPlaying"], contexts: ["", interaction])
}