UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Basic Swift UI - Modifiers?

Forums > SwiftUI

I've just made it through the swift part of the Hacking with iOS: SwiftUI course and and working through the Swift UI projects...but I'm missing something.

In this basic SwiftUI code:


struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
    }

I think I understand that:

Content View is a struct that conforms to the View protocol

body is a computed property returning something that conforms to the View protocol

Text is a Protocol that conforms to View protocol

...but what is .padding()?

I understand its a "modifier" for the Text in the SwiftUI framework and I understand what it's purpose is, but what is in in Swift terms? Is that a function within the Text protocol?

Thanks

2      

Yes, SwiftUI modifiers are implemented as functions. Most are on the View protocol, but there are some that only apply to certain types of View, like Text.

padding(_:_:) is a modifier on the basic View protocol, so it can apply to any type of View.

Something like strikethrough(_:color:) is only implemented on the Text type of View.

You can see this most clearly when you create your own custom modifiers. The process involves creating a struct that conforms to the ViewModifier protocol. It is then applied using the modifier(_:) function on View. But you can also extend View with a custom function to apply your modifier.

From Apple's docs:

struct BorderedCaption: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.caption2)
            .padding(10)
            .overlay(
                RoundedRectangle(cornerRadius: 15)
                    .stroke(lineWidth: 1)
            )
            .foregroundColor(Color.blue)
    }
}

extension View {
    func borderedCaption() -> some View {
        modifier(BorderedCaption())
    }
}

//then in a View...
Text("Downtown Bus")
    .borderedCaption()

So you can see that .borderedCaption() is a function on View. Built-in modifiers are implemented the same way.

You don't have to create a custom function by extending View; you could just use .modifier(BorderedCaption()) instead. But it's cleaner the other way.

3      

Thanks @roosterboy! That is very helpfull.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.