BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.