Skip to content

Instantly share code, notes, and snippets.

@isoiphone
Last active February 11, 2025 05:07
Show Gist options
  • Save isoiphone/e024ab087b16160022393d991108f037 to your computer and use it in GitHub Desktop.
Save isoiphone/e024ab087b16160022393d991108f037 to your computer and use it in GitHub Desktop.
Presenting a Landscape-only UIViewController on top of a Portrait-only UIViewController
// This should not be difficult, but it is.
// If you miss the `isBeingPresented` check it breaks.
// it will force the portrait only viewcontroller into landscape (an unsupported orientation!) during dismiss
import UIKit
class ViewController: UIViewController {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
.portrait
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .lightGray
view.layer.borderColor = UIColor.blue.cgColor
view.layer.borderWidth = 4
let button = UIButton()
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
button.setTitle("tap to push to landscape", for: .normal)
button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
}
@objc func didTapButton() {
view.window?.layer.speed = 0.25
let vc = LandscapeOnlyVC()
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
}
class LandscapeOnlyVC: UIViewController {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
isBeingPresented ? .landscape : .all
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .darkGray
view.layer.borderColor = UIColor.red.cgColor
view.layer.borderWidth = 4
let button = UIButton()
view.addSubview(button)
button.setTitle("tap to dismiss to portrait", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
}
@objc func didTapButton() {
dismiss(animated: true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment