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

"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)

2      

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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.