Swift - How to detect orientation changes
let const = "Background" //image name
let const2 = "GreyBackground" // image name
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(named: const)
// Do any additional setup after loading the view.
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("Landscape")
imageView.image = UIImage(named: const2)
} else {
print("Portrait")
imageView.image = UIImage(named: const)
}
}
How to detect orientation change?
Here's how I got it working:
In AppDelegate.swift
inside the didFinishLaunchingWithOptions
function I put:
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
and then inside the AppDelegate class I put the following function:
func rotated() {
if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
print("Landscape")
}
if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
print("Portrait")
}
}
Hope this helps anyone else!
Thanks!
How to update the UI when the device orientation changed in Swift?
Actually by using
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
you assign a frame to your login view which will not change on device rotation.
you might wanna use a constraint approach here as well:
// try replacing
// loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
// with
loginView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
loginView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
loginView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
loginView.topAnchor.constraint(equalTo: view.topAnchor),
loginView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
Another approach would be updating the frame of your login view e.g.
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
}
Last but not least you can use autoresizingMask in viewDidLoad
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
loginView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
P.S. My previous comment was misleading since the login frame wasn't set in the setupStackView() function
and my final comment:
// you can replace
loginView.frame = CGRect(origin: .zero, size: view.bounds.size)
// with
loginView.frame = view.bounds
Detect iOS device orientation change without rotating view
I think you can subscribe to a notification
final class ViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, #selector(handleOrientationChange, name: UIDevice.orientationDidChangeNotification, object: nil))
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc
private func handleOrientationChange() {
// Yay, orientation changed!
}
}
Swift Detect Every Time Device Orientation Changes
You may want to look into constraints so that your game looks good in both portrait and landscape if that is what you are wanting to support. You could set your constraints in storyboard then press vary for traits and choose the landscape option to set your new constraints for landscape.
Else, if you really needed to check orientation changes you could try:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
}
func rotated() {
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else {
print("Portrait")
}
}
Source
iOS Swift 5 Change device orientation manually
One simple way to accomplish this is by setting your supported orientation on the AppDelegate
(_:supportedInterfaceOrientationsFor:)
Create a local variable there
var orientation: UIInterfaceOrientationMask = .portrait
and then return that variable as supported orientation
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return orientation
}
on the ViewController
that you want to rotate with a touch of a button, you can change the supported orientation on the app delegate and than force the device orientation to change so that the view is rotated
private func changeSupportedOrientation() {
let delegate = UIApplication.shared.delegate as! AppDelegate
switch delegate.orientation {
case .portrait:
delegate.orientation = .landscapeLeft
default:
delegate.orientation = .portrait
}
}
@IBAction func rotateButtonTapped(_ sender: UIButton) {
changeSupportedOrientation()
switch UIDevice.current.orientation {
case .landscapeLeft:
UIDevice.current.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation")
default:
UIDevice.current.setValue(UIDeviceOrientation.landscapeLeft.rawValue, forKey: "orientation")
}
}
this will force the orientation of the device to change and then rotate your view. If you tap on the button again the orientation will be back to .portrait
Please be careful of using this as you need to really consider your navigation stack to make sure that only the top of the navigation stack support rotation and can only be pop from the navigation stack after the orientation is set back to the original which is .portrait
only.
How to check Device Orientation Change From Portrait To Landscape and Vice-Versa in iPad
From iOS 8.0 You can detect the orientation change using below method.
In objective-c
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
in swift
func viewWillTransitionToSize(_ size: CGSize,
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
from the size you can find out.
Related Topics
Center Content of Uiscrollview When Smaller
How to Get the Font Name from an Otf or Ttf File
Using Nsuserdefaults with Xcode 8 and iOS 10
How to Add iPhone 5 Large Screen Support to iOS Apps in Xcode
How to Remove Provisioning Profiles from Xcode
How to Read Data Structure from .Plist File into Nsarray
iPhone "Slide to Unlock" Animation
How to Keep Uitableview Contentoffset After Calling -Reloaddata
Should I Declare Variables in Interface or Using Property in Objective-C Arc
How to Make a Button Continually Call a Function When Held Down (Spritekit)
iOS 6 Facebook Posting Procedure Ends Up with "Remote_App_Id Does Not Match Stored Id"
Perform Background Tasks When App Is Terminated