Skip to content

Instantly share code, notes, and snippets.

@Geri-Borbas
Last active April 6, 2022 06:46
Show Gist options
  • Save Geri-Borbas/a35af5129b116d5e0289ad66fc7a7148 to your computer and use it in GitHub Desktop.
Save Geri-Borbas/a35af5129b116d5e0289ad66fc7a7148 to your computer and use it in GitHub Desktop.
import SwiftUI
struct SettingsView: View {
@State var isPortraitOnlyViewPresented = false
var body: some View {
List {
Section {
Button {
isPortraitOnlyViewPresented = true
} label: {
Text("Present Portrait-Only View")
}
}
}
.background(PresenterView(isPortraitOnlyViewPresented: $isPortraitOnlyViewPresented))
}
}
struct PresenterView: UIViewControllerRepresentable {
@Binding var isPortraitOnlyViewPresented: Bool
func makeUIViewController(context: Context) -> PresenterViewController {
return PresenterViewController()
}
func updateUIViewController(_ uiViewController: PresenterViewController, context: Context) {
if isPortraitOnlyViewPresented {
uiViewController.present()
}
}
}
class PresenterViewController: UIViewController {
func present() {
let viewController = ExamplePortraitOnlyViewController()
viewController.modalPresentationStyle = .fullScreen
present(viewController, animated: true)
}
}
class ExamplePortraitOnlyViewController: UIViewController {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
.portrait
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
let action = UIAction { _ in self.dismiss(animated: true) }
let button = UIButton(type: .system, primaryAction: action)
button.setTitle("Dismiss", for: .normal)
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
button.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
button.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
button.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment