NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

"How to store views as properties"

Forums > SwiftUI

On https://www.hackingwithswift.com/quick-start/swiftui/how-to-store-views-as-properties Can anyone explain why does adding a modifier like .padding(10) break it? thanks! (And how can i make this work to accomplish my goal?)

This is fine: let title = Text("Paul Hudson") .bold()

But this breaks: let title = Text("Paul Hudson") .bold() .padding(10)

   

I think it's because the return types of the two functions are different.

bold() returns a Text type.

padding() returns the opaque some View. The type is no longer known and Swift cannot infer it. You can therefore not assign it to a constant.

These are two solutions to your problem:

let title: some View = Text("Paul Hudson").bold().padding(10)
struct ContentView: View {
    let title = Text("Paul Hudson")
                     .bold()
    let subtitle = Text("Author")
                    .foregroundColor(.secondary)

    var body: some View {
        VStack {
            title
                .foregroundColor(.red)
                .padding(10)
            subtitle
        }
    }
}

These answers might help you: https://stackoverflow.com/questions/66333477/how-can-i-assign-value-of-some-view-to-type-view-in-swiftui

https://stackoverflow.com/questions/73015537/swiftui-why-cant-i-make-a-stored-property-a-view-with-a-modifier

   

Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

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

Reply to this topic…

You need to create an account or log in to reply.

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.