Skip to content

Instantly share code, notes, and snippets.

@pyxn
Last active April 21, 2020 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyxn/84740bdf347a33b598fa579a3c325a7e to your computer and use it in GitHub Desktop.
Save pyxn/84740bdf347a33b598fa579a3c325a7e to your computer and use it in GitHub Desktop.
Code displays how to switch between Landscape and Portrait views on SwiftUI depending on the current device orientation. This is achieved by attaching "UIDevice.current.orientation" to a State variable and using a .onReceive modifier to detect when the current orientation is changed through the Notification Center Publisher.
//
// Orientation.swift
// Code Template
//
// Created by Pao Yu on 2020-04-18.
// Copyright © 2020 Yu Pao. All rights reserved.
//
import SwiftUI
struct MainView: View {
@State var orientation: UIDeviceOrientation = UIDevice.current.orientation
var body: some View {
GeometryReader { device in
ZStack {
if self.mvm.orientation.isLandscape {
LandscapeView()
} else if self.mvm.orientation.isPortrait {
PortraitView()
} else if device.size.width > device.size.height {
LandscapeView()
} else if device.size.width < device.size.height {
PortraitView()
} else {
LandscapeView()
}
} .edgesIgnoringSafeArea(.all)
.onReceive(NotificationCenter.Publisher(center: .default, name: UIDevice.orientationDidChangeNotification)) { _ in self.mvm.detectOrientation() }
.onAppear() { self.viewDidLoad() }
}
}
func viewDidLoad() {
// Load code goes here.
}
func detectOrientation() {
orientation = UIDevice.current.orientation
}
}
struct LandscapeView: View {
var body: some View {
HStack{
Text("Landscape")
}
}
}
struct PortraitView: View {
var body: some View {
HStack {
Text("Portrait")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment