Implementing Page Based Navigation for SwiftUI Apple Watch App

拥有回忆 提交于 2020-06-23 05:58:07

问题


I'm building an Apple Watch app in SwiftUI and would like to implement page based navigation so when users swipe left on the home screen, they are taken to another view.

I understand how to use NavigationLink to let users move from one screen to another, but not how to let users navigate from screen to screen by swiping left or right.

Does anyone know how this can be done?


回答1:


Here is a guide how to implement page-based navigation for watchOS using SwiftUI. The description is based on Hacking with watchOS, SwiftUI edition:

First, create a new SwiftUI view, for example called CounterView.

Secondly, create a subclass of WKHostingController to show that new SwiftUI view. Just copy the controller already existing in HostingController.swift and change its name to CounterHostingController. The file HostingController.swift then contains these two controllers:

class HostingController: WKHostingController<ContentView> {
    override var body: ContentView {
        return ContentView()
    }
}

class CounterHostingController: WKHostingController<CounterView> {
    override var body: CounterView {
        return CounterView()
    }
}

Thirdly, create a storyboard scene to store that newly created hosting controller by opening the file Interface.storyboard and clicking the + button in the top right of the Xcode window. Type in "Hosting Controller" in the search box, drag out a new Hosting Controller and move it next to the existing Hosting Controller. In the identity inspector (click on the fourth item in the second menu from the top on the right side of the Xcode window, the one showing a document with a picture on the top left corner and text floating around it), change Class to "CounterHostingController", then check the "Inherit Module From Target" box.

Fourth, in order to connect these two screens as pages of the same user interface, in the storyboard press Ctrl and click with the mouse on the original hosting controller and hold the keys while dragging the mouse pointer onto the new controller and, after releasing the mouse button, select "next page" for the relationship segue.




回答2:


You can use multiple WKHostingControllers to bind them into pages using Storyboard. Every WKHostingController will represent the page in your navigation flow.



来源:https://stackoverflow.com/questions/57331552/implementing-page-based-navigation-for-swiftui-apple-watch-app

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