DEV Community

loading...

Day 23 of 100 days of SwiftUi

sanmiade profile image Oluwasanmi Aderibigbe ・2 min read

I just completed day 23 of 100 days of SwiftUi. Today, I learnt a lot about SwiftUI views and modifiers.

SwiftUI uses structs for views. This is because structs are very lightweight. Structs allow us to model our data without the performance overhead of classes.

View Modifiers are methods used to modify the style of your views. Since views are structs, view modifiers always return a new view when applied to an existing view. Using extension functions, you can create your own custom view modifiers.
Custom modifiers allow you to reuse a chain of modifiers instead of copy-pasting them.

You can create a custom view modifier in Swift like so:

struct Title: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.largeTitle)
            .foregroundColor(.white)
    }
}

Text("Hello World")
    .modifier(Title())

Text("Sanmi")
    .modifier(Title())
Enter fullscreen mode Exit fullscreen mode

The code above creates a custom view modifier that takes a view and returns a new view with a large title font and white background applied.

Since structs are used as Views in SwiftUI instead of classes. That means there's little to no performance overhead when they are destroyed and created anytime your app state changes. They also make us use composition instead of inheritance when modelling our views since Struct do not support Inheritance. This leads us to an approach called view composition. With view composition, you break down your UI into the smallest reusable component and compose them together to create your UI.
View composition in SwiftUI can be done like this

struct LargeText: View {
    var text: String

    var body: some View {
        Text(text)
            .font(.largeTitle)
            .foregroundColor(.white)
    }
}

struct ContentView: View {
    var body: some View {
        VStack(spacing: 10) {
            LargeText(text: "First")
            LargeText(text: "Second")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The code above creates two views the first is a large text view that takes a text and creates a TextView with a large font style and white text colour applied.
This view is then composed into SwiftUi ContentView. Instead of copy-pasting two TextViews into into SwiftUi ContentView, SwiftUI allows us extract our views and reuse them wherever we can

Discussion (0)

pic
Editor guide