How can I set portrait mode for the iPhone and for iPad portrait and landscape?

Viewed 172

I'm new to SwiftUI. My question is when the \user starts the app with an iPhone, they only can use the app in portrait mode. If the user starts the app with an iPad, it should be possible to use the app in portrait and landscape mode. I think I need UIDevice.current.model, but how can I implement this?

import SwiftUI
import UIKit

struct ContentView: View {
    @State var value_2 = 1
    @State var show_1 = false
    
    var body: some View {
        VStack {
            Button(action: {
                self.show_1.toggle()
            }) {
                    Text("Push")
                }
            .sheet(isPresented: $show_1) {
                Sheet(show_0: self.$show_1, value_1: self.$value_2)
            }
        }
    }
}

struct Sheet: View {
    @Binding var show_0: Bool
    @Binding var value_1: Int
    
    var body: some View {
        NavigationView {
            number(value_0: $value_1)
                .navigationBarTitle(Text("Enter number"), displayMode: .inline)
                .navigationBarItems(trailing: Button(action: {
                    self.show_0 = false
                }) {
                    Text("Done").bold()
            })
        }.navigationViewStyle(StackNavigationViewStyle())
    }
}

struct number: View {
    @Binding var value_0: Int
    
    var body: some View {
        Section {
            Text("Headline")
            Picker("",selection: $value_0)
                    {
                        ForEach(1..<101) { value in
                            Text("\(value)")
                }
            }
        }
        .labelsHidden()
    }
}
1 Answers

You can use @Environment(\.horizontalSizeClass) var sizeClass as explained here: Changing a view’s layout in response to size classes

That will tell us whether we have a regular or compact size class. Very roughly:

  • All iPhones in portrait have compact width and regular height.
  • Most iPhones in landscape have compact width and compact height.
  • Large iPhones (Plus-sized and Max devices) in landscape have regular width and compact height.
  • All iPads in both orientations have regular width and regular height.

You can use it this way:

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

    var body: some View {
        HStack {
            if sizeClass == .compact {
                // compact view
            } else {
                // ...
            }
        }
    }
}
Related