简体   繁体   中英

How to navigate between screens using a button in SwiftUI

代码

Hello, I want to navigate between windows using a button but not use a NavigationLink . It looks ugly. this is my code

import SwiftUI

struct ContentView: View {

    var body: some View {
        Button(action: action()){
            Text("Hola")
                .font(.largeTitle)
                .frame(width: 100, height: 100)
            .background(Color.red)
        }

    }
}

You can use an empty NavigationLink and bind your navigation flag or destination to your Button .

struct FirstView: View {
    
    @State var navigationFlag = false
    
    var body: some View {
        NavigationView {
            VStack {
                Text("First View")
                
                Button(action: {
                    self.navigationFlag = true
                }, label: {
                    Text("navigate")
                })
                
                NavigationLink(destination: SecondView(),
                               isActive: self.$navigationFlag,
                               label: {
                                EmptyView()
                               })
            }
        }
    }
    
}

struct SecondView: View {
    
    var body: some View {
        Text("Second View")
    }
    
}

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