I’m new to Swift and having experience with couple other languages, including JAVA, I must say that Swift is by far the weirdest..
I followed a tutorial on how to create a "switch" view in which I can switch between other views without using NavigationLink
I have those files
Helpfer.swift:
import Foundation
enum Page {
case login
case register
}
ViewRouter.swift
import SwiftUI
class ViewRouter: ObservableObject {
@Published var currentPage: Page = Page.login
}
As you can see the page login is pre set
In the ContentView I have a NavigationLink leading to the "switch" view:
NavigationLink(destination: SwitchView(viewRouter: ViewRouter(), showThisPage: .register).navigationBarBackButtonHidden(true), label: {
Text("go to switch view")
})
as you can see I want register
to be set instead of login
this time
I tried all kind of stuff in the SwitchView, this was the last:
import SwiftUI
struct SwitchView: View {
@StateObject var viewRouter: ViewRouter
var showThisPage: Page
var body: some View {
switch viewRouter.currentPage {
case .login:
Login(viewRouter: viewRouter)
case .register:
CreateAccount(viewRouter: viewRouter)
}
}
}
struct SwitchView_Previews: PreviewProvider {
static var previews: some View {
SwitchView(viewRouter: ViewRouter(), showThisPage: Page)
}
}
and get:
Cannot convert value of type 'Page.Type' to expected argument type 'Page'
EDIT:
It looks like nobody understands what I want, so again and more clearly:
I need to pass showThisPage: .register
through NavigationLink in ContentView
to SwitchView
and in SwitchView
I need to catch this value and use it to be recognized in
case .register:
CreateAccount(viewRouter: viewRouter)
}
How?
2
Answers
You must assign a value to
showThisPage
in your preview, so replace this:with:
Besides, you’re not using
showThisPage
in your code.Page is the type of the parameter. You have to give the value, not the Type.
You should use it like this: