how to change a view from portrait mode to landscape mode and lock it?
It's caused by this function,
func application(_ application: UIApplication,
supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return shouldRotate ? .allButUpsideDown : .portrait
}
change .allButUpsideDown
to .landscape
will do.
workable code,
AppDelegate.swift
func application(_ application: UIApplication,
supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return shouldRotate ? .landscape : .portrait
}
view controller,
func expandPlayerWindow() {
self.player.view.frame = CGRect(x:0, y:-20, width: UIScreen.main.bounds.maxY, height: UIScreen.main.bounds.maxX)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.shouldRotate = true // or false to disable rotation
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
appDelegate.shouldRotate = true
UIApplication.shared.isStatusBarHidden = true
}
Lock the orientation of the app in a specific View Controller in Swift
You can force orientation with few steps:
Firstly, In your AppDelegate
define a orientation property and conform supportedInterfaceOrientationsFor
var orientationLock = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}
Then declare utility struct to set orientation using KVO:
struct AppOrientationUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
How to use:
//For portrait
AppOrientationUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)
//For landscape
AppOrientationUtility.lockOrientation(UIInterfaceOrientationMask.landscapeRight, andRotateTo: UIInterfaceOrientation.landscapeRight)
How to lock orientation of one view controller to portrait mode only in Swift
Things can get quite messy when you have a complicated view hierarchy, like having multiple navigation controllers and/or tab view controllers.
This implementation puts it on the individual view controllers to set when they would like to lock orientations, instead of relying on the App Delegate to find them by iterating through subviews.
Swift 3, 4, 5
In AppDelegate:
/// set orientations you want to be allowed in this property by default
var orientationLock = UIInterfaceOrientationMask.all
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}
In some other global struct or helper class, here I created AppUtility:
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
/// OPTIONAL Added method to adjust lock and rotate to the desired orientation
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
}
}
Then in the desired ViewController you want to lock orientations:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
AppUtility.lockOrientation(.portrait)
// Or to rotate and lock
// AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Don't forget to reset when view is being removed
AppUtility.lockOrientation(.all)
}
If iPad or Universal App
Make sure that "Requires full screen" is checked in Target Settings -> General -> Deployment Info. supportedInterfaceOrientationsFor
delegate will not get called if that is not checked.
Flutter: How to set and lock screen orientation on-demand
First import the services package:
import 'package:flutter/services.dart';
This will give you access to the SystemChrome
class, which "Controls specific aspects of the operating system's graphical interface and how it interacts with the application."
When you load the Widget, do something like this:
@override
void initState(){
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
}
then when I leave the page, put it back to normal like this:
@override
dispose(){
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
super.dispose();
}
SwiftUI 5: How to lock orientation for a specific view
Well it turns out I've fixed the rotation instead:
func updateUIView(_ uiView: UIViewType, context: Context) {
let view = UIView(frame: UIScreen.main.bounds)
let statusBarOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
let videoOrientation: AVCaptureVideoOrientation = statusBarOrientation?.videoOrientation ?? .portrait
camera.preview.frame = view.frame
camera.preview.connection?.videoOrientation = videoOrientation
}
For videoOrientation
see Jack's answer.
import AVFoundation
extension UIInterfaceOrientation {
var videoOrientation: AVCaptureVideoOrientation? {
switch self {
case .portraitUpsideDown: return .portraitUpsideDown
case .landscapeRight: return .landscapeRight
case .landscapeLeft: return .landscapeLeft
case .portrait: return .portrait
default: return nil
}
}
}
xcode - How do I keep views locked into portrait mode, but still allow one view to rotate?
Add an observer to the viewDidLoad method of the view you want to rotate like this :
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];
and then set the views according the the landscape view inside the orientationChanged method like this :
- (void) orientationChanged:(NSNotification *)note{
UIDevice * device = [UIDevice currentDevice];
switch(device.orientation)
{
case UIDeviceOrientationPortrait:
break;
case UIDeviceOrientationPortraitUpsideDown:
break;
case UIDeviceOrientationLandscapeLeft:
break;
case UIDeviceOrientationLandscapeRight:
break;
default:
break;
};
}
Related Topics
Increment Tab Bar Badge W/ Uialertaction Swift
Swift 4: Timer Crashing - Unrecognized Selector Sent to Instance
How to Find the Index of a Tuple Element from an Tuple Array? iOS, Swift
Showing Hidden View Really Slow
Swift and Nsuserdefaults - Exc_Bad_Instruction When User Defaults Empty
How to Detect Which Image Has Been Tapped in Swift
Check the JSON Response Is Array or Int or String for a Key
How to Call the Apple Wallet from iOS App Using Swift
A Simple Code to Detect Any Beacon in Swift
Get the Exact Difference Between 2 Dates for a Single Nsdatecomponent
Error After Importing Swift into Objective-C
Coretelephony Esim Functions Not Working on Device
iOS PDFkit Displaymode = Singlepage Only Shows the First Page of the PDF
How to Convert Base64 into Nsdata in Swift
In Swift, for Anyobject, How to Setvalue() Then Call Valueforkey()
Scrolling in Uicollectionview Selects Wrongs Cells - Swift
Routing Between Points with Mapbox
How to Instantiate and Load a View Controller Before Segueing to It Using Swift