Getting started with SwiftUI


During the WWDC19, Apple introduced a new UI framework : SwiftUI Apple described SwiftUI to be:

The code is reduced, he’s now about 20% of what we had before in UIKit.

How does it works?

Views

The are two big differences between View and UIView:

  1. View is a protocol, UIView is a class.
  2. You’ll always need to return a view to render.

Here’s the base code when you ceate an app with SwiftUI

struct ContentView : View {
    var body: some View {
        Text("Hello World")
    }
}

You can see that:

  1. It returns some View
  2. UILabel in UIKit is Text in SwiftUI

View always returns 1 thing. If you want to display multiple labels, you’ll need to place them inside a container.

Live preview

As you can see, the view on the iPhone updates in live when we edit code.

And vice versa...

When we add something in the preview on the iPhone, it updates the code

Containers

Here are the tree containers that remplace UIStackView:

The stacks take up only the space they need. If you want to add some space, add:

Text

Adding Text is very simple:

Text("Hello World")

This is all you need!

Know that you can cusomize your text like that:

Text("Hello World")
    .font(.title)
    .frame(width: 10.0)
    .fontWeight(.thin)

and many others…

Note

What is good to know is that you can add items from both code and preview.

By holding cmd and clicking on you item in code or preview offers you a lot of possibilities like embed in stack. It’s very close of UIKit.

I’m not planning to do a lot of tutorials on SwiftUI. Apple did a lot of tutorials here You can find also a lot on the web. I was just presenting and introducing SwiftUI.

But, if you want me to do some tutorials, let me know and contact me!

If you liked this post, share it with your friends or should you have any feedback, contact me