Getting started with SwiftUI to build your declarative interface

- Andrés Cruz

En español

Getting started with SwiftUI to build your declarative interface

SwiftUI is a powerful framework that just came out of the oven and was recently presented at Apple's WWDC in June of this year; It is a framework that only works to create apps on iOS 13 and up and today we will see an introduction to this framework that allows us to create interfaces much more easily and with fewer lines of code than with the traditional approach.

Why develop our applications in SwiftUI?

With this powerful framework, we can develop under a single code for practically all Apple platforms, from macOS, watchOS to the new iPadOS and of course iOS; We can create our applications through a library that offers us an interface for our components, a declarative library as we do to create our Flutter applications but with Swift.

The logic for writing an app in SwiftUI is much simpler than in Swift; to build an application in Swift you must at least work in two sections, the view through the main storyboard and the controller. In SwiftUI we can do everything from a file with a .swift extension in which we somehow contain the controller and the view.

Multiple files and structures to define your view components (lists, buttons, etc) in SwiftUI

The basic structure is similar to that of Flutter, in which we have a kind of tree of widgets or if you want to see it more generic, of components that we go deeper as we have more and more elements or these are more complete and complex.

Another fundamental point is that we can develop multiple components (a group of view elements) in the same file; therefore we can fragment our interface into multiple components, for example, one component for a list, another for the detail or each item in that list, and another for the header (for example):

struct CoruseView : View {
    var course = coursesData[0]
    
    var body: some View {
       
        return VStack(alignment: .leading) {
            Text(course.title)
                .font(.title)
                .fontWeight(.bold)
                .foregroundColor(.white)
                .padding(20)
                .lineLimit(4)
                //.frame(width: 150)
            Spacer()
            Image(course.image)
                .resizable()
                .renderingMode(.original)
                .aspectRatio(contentMode: .fit)
                .frame(width: 246, height: 150)
            .padding(.bottom, 30)
            }.background(course.color)
            .cornerRadius(30)
            .frame(width: 246, height: 360)
            .shadow(color: course.shadowColor, radius: 20, x: 0, y: 0)
       
    }
}

And in our main view:

            ScrollView(showsHorizontalIndicator: false) {
                HStack(spacing: 30) {
                    // ForEach(0 ..< 3) { item in
                    ForEach(courses) { course in
                        NavigationLink(destination: CoruseView(course: course)) {
                            CoruseView()
                        }
                    }
                    }.padding(.leading, 50)
            }

And we can save all this in the same file or in different files, in different folders, which brings us a good and a bad point; The good thing is that we can organize our project as we want in multiple folders/files, etc. and the bad thing is also precisely that point, that by not having a fixed organization, it can cause us problems when working with other people's projects or in a work team. .

Iterate view elements

With SwiftUI we can easily iterate view elements through a ForEach structure and in this way avoid replicating them manually. For example, to have a simple list of elements you need a List component and within it a Text component:

List {
    ForEach(categories.identified(by: \.self)) { key in
        Text(key)
    }
}

For example, if we have a user structure:

        NavigationView{
            VStack {
                List{
                    ForEach(users) { user in
                        Text(user.username)
                    }
                }.navigationBarTitle(Text("Personajes"))
                
            }
        }
Listado simple con SwiftUI

This is simply declarative, it is a way of doing it, the only thing you have to keep in mind is that with a ForEach we can create view elements dynamically.

Of course, this list of categories must have a structure that we will see later in another post...

ForEach, HStack to stack images and texts horizontally

Now, if you want to have a more interesting list, you could create another component and set an image and a text; therefore, now you would have 3 components (not counting the text and image components that you are using in this same component) and we take advantage of one and indicate that we want to place an alignment; Just as it happens with the LinearLayout in Android or the same VStack in classic Swift, here we have a couple of components to align or place elements vertically or horizontally:

List {
ForEach(categories.identified(by: \.self)) { key in
   HStack(alignment: .top, spacing: 0) {
        Image(key.image)
        Text(key.name)
    }
}

And with the alignment parameter we can align them towards the top, bottom, leading and then we indicate that we don't want spacing.

Reuse components in other files

Previously I told you that we could fragment a view, which corresponds to a single file into multiple components that in the end were structs that contained our view elements; but as you see, we are having more code and we can perfectly place all that in a separate file and in this way be able to reuse them when we want and have a better order:

struct CategoryItem: View {
   var landmark: Landmark
   var body: some View {
       VStack(alignment: .leading) {
           landmark
               .image(forSize: 155)
               .cornerRadius(5)
           Text(landmark.name)
               .font(.caption)
       }
       .padding(.leading, 15)
   }
}

You can save this code in a new SwiftUI type file with the name you want.

The component is a struct and it looks like the one shown in the previous example, in which it receives data as a parameter, which is what we are going to use to build the component, which we place in a Stack view or vertical stack and simply we place an image (whose component is the Image) and a text, we also use a series of functions that are known as modifiers to customize styles of these elements.

Now, we can use this new compound block created by us in any other component, for example, the main component:

ScrollView(showsHorizontalIndicator: false) {
    HStack(alignment: .top, spacing: 0) {
        ForEach(self.items) { landmark in
            CategoryItem(landmark: landmark)
        }
    }
}

Resources and tutorials to develop your applications in SwiftUI

Of course you are going to want more than a list, for example, a promotional image which would be another component that can have other components, either the bases or one defined by you; As we exemplified before, you can create all the components you want, add them as many times as you want and give it the shape you want your application to have.

Here the purpose of these examples is more that you understand the code that we will analyze little by little and I also leave you at the end of the post some free video tutorials so that you can start creating your applications with SwiftUI, it is that you see the programming logic and the way in which we can build our applications as if they were building blocks.

In the same way, your best ally is the official documentation in the following link..

This is an idea that is not new, but it is very interesting, it allows us to develop more quickly since we are building with lego blocks, lego blocks where each block is a different component that can be a text, a list, an image or one created by you.

We can have the data locally in files, json, or any other component or bring it to us from a server.

We can give our components a state, which in other words means that changing the state changes our associated components directly and immediately; in this way we save a lot, but a lot of code.

You can see in the previous video and realize the difference; this time we are declaring elements of the view, in our file, just as Flutter makes all our interface components are Widgets, here we have a similar organization in which we compose elements that reference an interface element through code, and we can extend its features by functions.

Xcode to develop your applications with SwiftUI

To develop your applications in SwiftUI it is necessary that you have xCode 11 or later, which is currently in beta phase; It is a somewhat heavy framework, about 11 GB, but when you have it downloaded and installed on your Mac (installation is traditional in Mac environments) you will be ready to start developing your first applications; you can download it from the following Using Apple Beta Software page.

On the official Apple site you can get tutorials so you know how to start working with this interesting framework that Apple offers us: SwiftUI Better apps. Less code Here you will see resources, descriptions and an interesting tutorial to take the first steps.

And of course, the official documentation, without examples or anything to distract you: SwiftUI Framework.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 2d 17:27!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!