TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Button to bring up a new View in SwiftUI

Forums > SwiftUI

Hi, it's me again!

By GOD'S Grace, I am trying to use a button to trigger another View in SwiftUI.

I don’t want to use NavigationStack and NavigationLink as I don’t have much knowledge about it.

But rather, have a simple button that brings up another view.

Is it possible to create such an action (display another View) with just a button and how, please?

Many thanks in advance and GOD bless us all. :)

   

Well does seem a loaded question! As you have put this in SwiftUI group, I am assuming that the UIView conforms to View. Then you can do a number of ways :-

  1. Boolean sheet
  2. Optional Sheet
  3. Navigation Link Boolean
  4. There are are a few more!

    struct ContentView: View {
    // Boolean sheet
    @State private var showSheet = false
    
    // Optional Sheet
    @State private var someModel: SomeModel?
    
    // Navigation Link Boolean
    @State private var showNavLink = false
    
    var body: some View {
        NavigationStack {
            VStack(spacing: 30) {
                Button("Show Boolean Sheet") {
                    showSheet = true
                }
                .buttonStyle(.bordered)
    
                Button("Show Optional Sheet") {
                    someModel = SomeModel(name: "PhelaTK")
                }
                .buttonStyle(.bordered)
    
                Button("Navigation Link") {
                    showNavLink = true
                }
                .buttonStyle(.bordered)
            }
            .padding()
            // Boolean sheet
            .sheet(isPresented: $showSheet) {
                Text("Boolean Sheet View")
            }
            // Optional Sheet
            .sheet(item: $someModel) { someModel in
                Text("Optional Sheet View, \(someModel.name)")
            }
            .navigationDestination(isPresented: $showNavLink) {
                Text("Boolean Navigation Link View")
            }
        }
      }
    }
    // this is a dummy model for passing in data to new view
    struct SomeModel: Identifiable {
    let id = UUID()
    let name: String
    }

    Where the Text("......... View") is where you put the View

1      

Thanks so much. Will give it a try, please :)

   

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.