简体   繁体   中英

How to move to another View by button using a SwiftUI - swift 5.5

For Example, This a view:

struct ContentA: View {
var body: some View {
   Text(“Hello”)
    }
}

struct ContentB: View {
var body: some View {

Button("Lets Go!") {
         // Here i wanna to move to ContentA view   
        }
    }
}

I want a way to reach the ContentA View by the button.

like this photo: Here

The easiest way to do this with SwiftUI is NavigationLink . I have tested this solution to work. You can also show a View as a Sheet. I'd look here for that solution. https://www.hackingwithswift.com/quick-start/swiftui/how-to-present-a-new-view-using-sheets

I believe the NavigationLink solution requires you to have NavigationView as well.

import SwiftUI

struct ContentA: View {
var body: some View {
    Text("Hello")
    }
}

struct ContentB: View {
var body: some View {
    NavigationView {
        NavigationLink("Link to A", destination: ContentA())
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentB()
    }
}

You can do this via this simple call to the specific view you want to reach. If you want to reach contentAView then just call it in the buttons action space like so

struct ContentA: View {
    var body: some View {
       Text("Hello")
        }
    }
    
struct ContentB: View {
    @State var showContentA = false
    var body: some View {
        
        NavigationView{
            Button("Lets Go!") {
                showContentA = true
                
            }
        }
        .sheet(isPresented: $showContentA) {
            ContentA()
        }
    }
}

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