Use button 'action' to change view

Hi guy/girls
First off, I’m a neeb Swift coder, currently doing Chris “iOS Foundations with SwiftUI (2023)” course.
I’m at module 3 lesson 5, so my question may be a bit early to ask, but I’ve looked into the later modules (and Googled) but haven’t been able to find out how to do this, or if it’s even possible.

I want to use a button as, well a button and use it for changing view upon press, through button action.
My challenge may stem from how I have structure my app, but first the background of my structure.
I have broken down my views, and made a menu view that contains 5 buttons intended to open 5 different views. The menu goes across the whole app, with a few button changing here and there.

The buttons are grouped in a “Menu” view in a HStack.
The “Menu” is then called from my “ContentView” by Menu() located in a VStack (Inside a ZStack).
What I essentially want is for my menu button to change what view is showed in accordance with the view mentioned in the “buttonAction” as shown below.

                buttonTitle: "Home",
                buttonImage: "",
                buttonAspecRatio: .fit,
                buttonForegroundColor: .white,
                buttonAction: { HomeView() })

Is what I’m trying to do possible in Swift, and if, how do I make it work?
If more of the projects code is needed to make sense of my question please let me know and I will try to provide it.
(Holding back code if not needed to avoid cause more confusion)

/ Have a great day C.


Hi Casper,

Welcome to the community.

I edited your post since you pasted the same content twice in the message body.

By the looks of the image you posted you have that menu along the bottom of the screen and what you appear to be trying to do is effectively what a TabView does.

If you want to use your own Custom “TabView”, where the buttons change dynamically depending on where you are in the App, then the method you need to use to present a specific view (the screen you want to see) can’t be by defining that View in your button action code. SwiftUI will not understand how to deal with that.

What you need to do is trigger a boolean value (or change an enum value) where you display a View based on an if statement (or an enum selection).

If you have a look at the Chat App course that Chris Ching has on CWC+, it shows how to create a Custom TabBar (much like you are doing) where the current View that is visible is based on changing an enum.