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'
So how to do this correctly? Is it even possible? I've read that swift is very limited and you can't do much with it
CodePudding user response:
Page is the type of the parameter. You have to give the value, not the Type. You should use it like this:
struct SwitchView_Previews: PreviewProvider { static var previews: some View { SwitchView(viewRouter: ViewRouter(), showThisPage: .register) } }
CodePudding user response:
You must assign a value to showThisPage
in your preview, so replace this:
SwitchView(viewRouter: ViewRouter(), showThisPage: Page)
with:
SwitchView(viewRouter: ViewRouter(), showThisPage: Page.login) //or Page.register
Besides, you're not using showThisPage
in your code.