Last active
April 21, 2020 18:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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