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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.