|
/** |
|
* Add the sbs_forcedSupportedInterfaceOrientations property to UIViewController. We'll swizzle UIViewController to return |
|
* the value of sbs_forcedSupportedInterfaceOrientations in supportedInterfaceOrientations when it's set to anything but nil. |
|
* Setting this value disables rotation in the view controller but does not guarantee that the view controller is presented |
|
* with the required orientation. We'll enforce this immediately before presenting the view controller. |
|
*/ |
|
|
|
import UIKit |
|
|
|
private var forcedSupportedInterfaceOrientationsKey: Void? |
|
extension UIViewController { |
|
var sbs_forcedSupportedInterfaceOrientations: UIInterfaceOrientationMask? { |
|
get { |
|
if let boxedValue = objc_getAssociatedObject(self, &forcedSupportedInterfaceOrientationsKey) as? NSNumber { |
|
return UIInterfaceOrientationMask(rawValue: boxedValue.uintValue) |
|
} else { |
|
return nil |
|
} |
|
} |
|
set { |
|
if let newValue = newValue { |
|
let number = NSNumber(value: newValue.rawValue) |
|
objc_setAssociatedObject(self, &forcedSupportedInterfaceOrientationsKey, number, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) |
|
} else { |
|
objc_setAssociatedObject(self, &forcedSupportedInterfaceOrientationsKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) |
|
} |
|
} |
|
} |
|
} |
|
|
|
// Swizzle UIViewController to use our sbs_supportedInterfaceOrientations. |
|
extension UIViewController { |
|
// Make sure to call this early in the app's lifecycle. |
|
static let classInit_supportedInterfaceOrientations: Void = { |
|
if let originalMethod = class_getInstanceMethod(UIViewController.self, #selector(getter: supportedInterfaceOrientations)), |
|
let swizzledMethod = class_getInstanceMethod(UIViewController.self, #selector(getter: sbs_supportedInterfaceOrientations)) { |
|
method_exchangeImplementations(originalMethod, swizzledMethod) |
|
} |
|
}() |
|
|
|
@objc var sbs_supportedInterfaceOrientations: UIInterfaceOrientationMask { |
|
if let forcedInterfaceOrientation = sbs_forcedSupportedInterfaceOrientations { |
|
return forcedInterfaceOrientation |
|
} else { |
|
return self.sbs_supportedInterfaceOrientations |
|
} |
|
} |
|
} |
Video demo in this tweet: https://twitter.com/simonbs/status/1511425074720555014