SwiftUI: conditional rendering according to the current device (iPhone or iPad)

Hello forum!
I have a grid in my app

I want to display 1 column if the user's device is iPhone
or 2 columns if the device is an iPad

How can I do that from SwiftUI?

Could you help me? thankS :grinning:

1 Like

Since this is about SwiftUI, and not the Swift language itself, this is somewhat off-topic and should probably be asked in the Apple Developer Forums

But also, in general, Apple's UI frameworks try to discourage changing your UI based on "iPhone or iPad", because your app should support multi-tasking and slide-over, which will present your app in a non-full-screen container on iPad.

The recommended approach is to do this conditionally based on the size class. You can read the current horizontal and vertical size classes via the SwiftUI Environment.

https://developer.apple.com/documentation/swiftui/environmentvalues/horizontalsizeclass

struct MyView: View {
  @Environment(\.horizontalSizeClass) var horizontalSizeClass

  var body: some View {
    LazyVGrid(columns: /* adjust the columns based on size class */) { ... }
  }
}
2 Likes

Thanks @harlanhaskins :smiley: