From the course: Complete Guide to SwiftUI

Add view

- [Instructor] So far, we've been working with the one ContentView in Swift UI. However, good Swift UI should be small multiple files each doing a smaller part of the full hierarchy. You'll be adding a lot of views to projects. So, let's go through how to add a view to an app. There's two primary ways to add views to an app. In Xcode, you can use the Swift UI template. Just go to File, New, File and you'll see under User Interface, Swift UI View, and you go ahead and hit Next. And then, just make sure you've got the right group and the right targets, and the right location for your file. And then, just change the name here. So I'm just going to make this one OrderView and then just create it. And that creates a new file here called OrderView. The second way. You can use both an Xcode and if you're using the Swift Playgrounds app. Instead of a template, you create a blank Swift file. So, let's do the same thing again, File, New, File. And this time I'm going to use a source of a Swift file and hit Next. Again, make sure my location, group, and targets are all correct. And now, I'm going to call this one MenuView and then go ahead and hit Create. So, if if a blank one like this, you're going to just do two things. First of all, I'm going to change foundation to Swift UI. And then under that type View, and you'll see here that the View protocol actually has an auto complete and it does some really nice things. It'll put both the view and the previews into your code. And second of all, it starts a refactoring so that you can change the name properly. And I'm going to call this MenuView. So, let's put in MenuView here. And it sets everything up for MenuView. So, I just hit return and now I'm set with this MenuView and I have a Swift UI file. Now, look at this carefully so that we see some structure that's going on here. A Swift UI View has one required property called body, which has a closure returning a view. All the code we are typing ends up in this view right here. So, you can code a view to that closure or copying it from another part of your code. You want lots of views in your project. With more and smaller files as you make them, you can make projects a lot more manageable.

Contents