1

I'm trying to implement a list in a Multiplatform implementation here is my implementation:

struct ContentView: View {
    var body: some View {
        List {
            Section(header: Text("Header"), footer: Text("Footer")){
                ForEach(0..<5){
                    Text("\($0)")
                        .tag($0)
                }
            }
            #if os(iOS)
                .listStyle(GroupedListStyle())
            #endif
        }
    }
}

But on this line:

.listStyle(GroupedListStyle())

I'm getting this error:

Unexpected platform condition (expected `os`, `arch`, or `swift`)

Any of you knows a way around this error?

I'll really appreciate your help

user2924482
  • 8,380
  • 23
  • 89
  • 173

1 Answers1

1

SwiftUI doesn't like conditional compilation code very much.

Try something like this:

#if os(macOS)
typealias MyListStyle = PlainListStyle
#else
typealias MyListStyle = GroupedListStyle
#endif
...
SomeView {}
.listStyle(MyListStyle())

Or

func myListStyle() -> some View {
    #if os(macOS)
    return listStyle(PlainListStyle())
    #else
    return listStyle(GroupedListStyle())
    #endif
}
...
SomeView {}
.myListStyle()

You can also use a variation of the func with a returned self for modifiers that aren't appropriate. I also used it to make .environment conditional.

David Reich
  • 709
  • 6
  • 14
  • I implemented your solution but I'm getting and error in this line `Section(header`, error: `Instance method "listStyle" requieres that some view conform to ListStyle` – user2924482 Sep 25 '20 at 21:10
  • You can only apply `.listStyle` to a `List` or maybe a form or a stack. It probably doesn't work on a `Section`. That's what the compiler is telling you. SwiftUI often has cryptic error messages, but this one is very plain and specific. – David Reich Sep 26 '20 at 05:26