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

SOLVED: Form/List conditional for iOS and MacOS

Forums > SwiftUI

I'm trying not to duplicate my views when adapting my iOS apps to MacOS. But in one view I have just a word to change for conditioning its display:

Form {
    Section {
        DisclosureGroup("First evaluation") {
            HStack {
                //...

I need to use "Form" for iOS and "List" for MacOS, due to scrolling questions. But conditionals I usually manage for that purpose...

#if os(iOS)
    //Form
#else
    //List
#endif

...can't be used here.

Is there anyway not having to duplicate all my view just for this word😅?

1      

You could try something like this

Set this up

struct FormList<Content: View>: View {
    @ViewBuilder let content: () -> Content

    var body: some View {
        #if os(iOS)
        Form {
            content()
        }
        #else
        List {
            content()
        }
        #endif
    }
}

Then you can use it as such

struct ContentView: View {
    var body: some View {
        FormList {
            Text("One")
            Text("Two")
            Text("Three")
            Text("Four")
            Text("Five")
        }
    }
}

I have not tested on macOS but seems to work on iOS

1      

That's exactly what I was looking for! Thank you sooo much.

1      

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!

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.