简体   繁体   中英

Change the view when a button is pressed in SwiftUI

I want to change the view when I press the button in SwiftUI.

ZStack {
    Button(action: {
        Settings(logOutAfter24H: true, emailAddress: "example@example.com")
        print("Button pressed")
    }) {
        ZStack {
            RoundedRectangle(cornerRadius: 10)
                .frame(width: 125, height: 150).foregroundColor(Color.CGreen)
            HStack {
                Image(systemName: "gear")
                Text("Settings").foregroundColor(Color.black)
            }
        }
    }
}

I want to switch to the Settings view.

If you just want your current View to be replaced with the SettingsView, you can try:

struct ContentView: View {
    @State var showSettingsView = false

    var body: some View {
        ZStack {
            if showSettingsView {
                Settings(...)
            } else {
                settingsButton
            }
        }
    }
    
    var settingsButton: some View {
        Button(action: {
            self.showSettingsView = true
            print("Button pressed")
        }) {
            ZStack {
                RoundedRectangle(cornerRadius: 10)
                    .frame(width: 125, height: 150).foregroundColor(.green)
                HStack {
                    Image(systemName: "gear")
                    Text("Settings").foregroundColor(Color.black)
                }
            }
        }
    }
}

By setting the value of showSettingsView you can decide whether to show or hide SettingsView.

Alternatively you can use a NavigationLink to push a new View on the navigation stack or use a sheet to present a view modally:

struct ContentView: View {
    @State var showSettingsView = false

    var body: some View {
        ZStack {
            settingsButton
        }
        .sheet(isPresented: $showSettingsView) {
            Settings(...)
        }
    }
    ...
}

Make a sheet for it or a navigation link. For a sheet, make an @State var called show = false. Then say self.show.toggle() in the button action, and then at the closing bracket of the parent view stack or the closing bracket for the button you can say .sheet and do the binding with $show and then for content, just say Settings(). If you want to make a navigation link instead, just delete the button and instead say NavigationLink(destination: Settings() { "configure button appearance here" }

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