We have the wireframe for the menu page of our takeout order app, but we have only one menu Item, and we probably want more than that. How can we get more items? Let’s find out.
Swift and SwiftUI are a modular language. You build small pieces that do one thing and then and fit them together.
SwiftUI has Views, but you can make your own from other views. The HStack we have for the menu item can be turned into a view we can use several time to get more menu items.
Let’s try this. New views need their own files, so first we create the file.
Open the side tab if It isn’t open yet
and tap the new file button.
Select Swift File from the menu that appears.
In the Code section of the sidebar, New File is highlighted so you can change the name to something else. When Making view we usually end with view. I’ll call this MenuItemView.
Tap in the code and the code change to alphabetical order.
In the code on Line 2 Type View and press return. All the required code for a view appears.In later lessons We’’l explain what this is all about. For now you’ll see that MyView is Highlighted in a rectangle. Change that to MenuItemView.
You’ll also notice the preview now has two dots and some arrows. Tap the arrows ad you’ll see the Hello world from the body. Delete that. And you get an error.
Tap Back to ContentView. Highlight all of the HStack Code.
Now go to MenuItemView. Paste it where Hello World was.
Preview should change to the menu Item code. IF it doesn’t ,try going to ContentView and then back to MenuItemView or leaving the app and returning to it.
You’ve made your own view. Now to use it.
Go back to Content View and under the divider, Type in
Menu Item show up again.
Add another MenuItemView Under that one. And we have two.
Making views like this is a big part of SwiftUI. You make smaller parts you assemble tog her in a view hierarchy that becomes your app.
With some of the major parts assembled we can start to add a little content. In the next lesson, we’ll Add some images in place of the circle and rectangle.
Leave a Reply