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)
}
}
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!
}
}
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
How to check if device orientation is landscape left or right in swift?
you can do something like,
if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft{
}
else if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight{
}
else if UIDevice.currentDevice().orientation == UIDeviceOrientation.UIDeviceOrientationPortraitUpsideDown{
}
else if UIDevice.currentDevice().orientation == UIDeviceOrientation.UIDeviceOrientationPortrait{
}
SWIFT 5
if UIDevice.current.orientation.isLandscape {
} else if UIDevice.current.orientation.isFlat {
} else if UIDevice.current.orientation.isPortrait {
} else if UIDevice.current.orientation.isValidInterfaceOrientation {
}
SWIFT 3
if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft {
} else if UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
} else if UIDevice.current.orientation == UIDeviceOrientation.portrait {
} else if UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown {
}
In Swift, how to get the device orientation correctly right after it's launched?
I have tested many times about orientation, so I have summed up some experience.
In all iPhone devices, except iPhone6(s) plus, the only interface orientation is .portrait
. If App is launched in landscape mode, there must be a change of orientation. One will receive the UIDeviceOrientationDidChangeNotification
. It's an appropriate time to get the orientation.
Regarding the launching when in landscape with iPhone6, the orientation after the launch will change once:
The launching when in landscape with iPhone6 plus, after launch the orientation never changed:
Two different screenshot with the same app,
So before the app does change orientation, the orientation is still like in the home page.
In viewDidLoad
, the orientation has not changed yet, the log will be the wrong direction.
Swift: Changing view/screen depending on device orientation. What is efficiency wise the better option?
I'd definitely go for an option number 2.
That way you encapsulate all the logic related to the calendar, for example for adding event or displaying it, in one view controller, without the need to reimplement the sane logic somewhere else (eg other view controller with landscape mode). Having two views for a different layout modes is not THAT easy to maintain, but if that's the only way to show the difference between the modes it really is a fine solution. And it's much easier to maintain than two view controllers with the very similar logic.
Get the current device orientation
You have nested functions - that won't work. Change it to this:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated) // No need for semicolon
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
test.backgroundColor = UIColor.purple
} else {
test.backgroundColor = UIColor.blue
}
}
In fact, you can get rid of the override for viewWillLayoutSubviews with the code you've shown.
Related Topics
Should I Declare Variables in Interface or Using Property in Objective-C Arc
Using Nsuserdefaults with Xcode 8 and iOS 10
Alamofire Invalid Value Around Character 0
What Should Xcode 6 Gitignore File Include
Secure Keys in iOS App Scenario, Is It Safe
How to Underline a Uilabel in Swift
iPhone In-App Purchase Store Kit Error -1003 "Cannot Connect to Itunes Store"
In iOS 12, When Does the Uicollectionview Layout Cells, Use Autolayout in Nib
Add Custom Header Field in Request of Avplayer
How to Make a Button Continually Call a Function When Held Down (Spritekit)
Table View Images Never Being Released
Uicollectionview Set Number of Columns
How to Check If a File Exists in the Documents Directory in Swift
Module Compiled with Swift 4.0 Cannot Be Imported in Swift 4.0.1