Learn Courses My Dashboard

Code to Open a new page when a button is clicked

I am new to the coding community. I have a text button on my app, I want it to open a new page when I click on it.

Please how do I do this?

Thank you

@chukawithchris
Is your project SwiftUI or UIKit (Storyboard)?

SwiftUI.

Button(action: {}, label: {
})
Text(“Login”).font(.largeTitle).foregroundColor(Color.green).padding()

// I want the “Login” to be a button, so that when I click it a login page will open.

Here is an example of presenting a Modal View and a Fullscreen Cover View.

struct ContentView: View {
    @State private var isShowingModalView = false
    @State private var isShowingCoverView = false

    var body: some View {
        VStack(spacing: 30) {
            Text("Hello, world!")
                .padding()
            Button("Present Modal View") {
                isShowingModalView = true
            }
            Button("Present Cover View") {
                isShowingCoverView = true
            }
        }
        .sheet(isPresented: $isShowingModalView) {
            ModalView()
        }
        .fullScreenCover(isPresented: $isShowingCoverView) {
            CoverView()
        }
    }
}

struct ModalView: View {
    var body: some View {
        ZStack {
            Color(.yellow)
                .edgesIgnoringSafeArea(.all)
            Text("Modal View!")
        }
    }
}

struct CoverView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        ZStack {
            Color(.green)
                .edgesIgnoringSafeArea(.all)
            VStack(spacing: 40) {
                Text("Cover View")
                Button("Dismiss View") {
                    dismiss()
                }
            }
        }
    }

    func dismiss() {
        presentationMode.wrappedValue.dismiss()
    }
}

Using your Button code example this is what you could do:

struct ContentView: View {
    @State private var isShowingLogin = false

    var body: some View {
        VStack {
            Button(action: {
                isShowingLogin = true
            }, label: {
                Text("Login")
                    .font(.largeTitle)
                    .foregroundColor(Color.green)
                    .padding()
            })
        }
        .fullScreenCover(isPresented: $isShowingLogin) {
            LoginView()
        }
    }
}

struct LoginView: View {
    var body: some View {
        ZStack {
            Color(.systemGreen)
                .ignoresSafeArea()
            Text("Login Page")
                .font(.largeTitle)
        }
    }
}

Thank you so very much. I am working on it now.

Thank you once again.