简体   繁体   中英

Present a new view when a condition has been met in SwiftUI

Hi everyone I'm new to SwiftUI .. I need to present a view containing two textFields with modal presentation only after a condition has been checked.


Example .. When the user pushes the login button I need the app to check the database for the existence of the user. If the user exists he can access the app otherwise he must show a view where he must enter his name and surname.

With UIKit I used this to present a structure or class

self.present(userFound ? Home() : UserNameInfo(), animated: true, completion: nil)

but with SwiftUI I can't figure out how to solve this problem.

Can you help me in any way?

You can use the modifier .fullScreenCover

& you just need to pass a binding to a @State var which you set to true when you want to display the modal.

example

struct ExampleScreenView: View {
    @State var showModal: Bool = false

    var body: some View {
        VStack {
            Text("Some Text")
                .padding()

            Button {
                showModal = true
            } label: {
                Text("Show other view")
            }
        }
        .fullScreenCover(isPresented: $showModal) {
            VStack {
                Color.white
                Text("Some other text")
                    .padding()

                Button {
                    showModal = false
                } label: {
                    Text("close view")
                }
            }
        }
    }
}

This example the first view has a button that sets the bool to true, and shows the modal, the modal view has a button that sets the bool to false and closes the view.

So once your login condition is met you can set a the boolean to true, and then you can present whatever view you choose within the fullScreenCover.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM