11. 具体的な実装
/** 適切なタイミングで回転をハンドリング */
private func hookForRotation() {
ObjcHelper.aspect_viewControllerHookSelector("viewWillAppear:", withOptions: .PositionBefore, error: nil) { info in
let vc = info.instance() as UIViewController
self.allowRotation = vc.allowRotation
}
// 非表示時にAppDelegateのallowRotationを切り替え
ObjcHelper.aspect_navigationControllerHookSelector("popViewControllerAnimated:", withOptions: .PositionBefore,
error: nil) { info in
let vc = info.instance() as UINavigationController
let vcs = vc.viewControllers
self.allowRotation = (vcs[vcs.count - 2] as UIViewController).allowRotation
}
ObjcHelper.aspect_viewControllerHookSelector("dismissViewControllerAnimated:completion:",
withOptions: .PositionBefore, error: nil) { info in
let vc = info.instance() as UIViewController
if let presentingViewController = vc.presentingViewController {
self.allowRotation = presentingViewController.allowRotation
}
}
// supportedInterfaceOrientationsの実装をすり替え
ObjcHelper.aspect_viewControllerHookSelector("supportedInterfaceOrientations", withOptions: .PositionInstead,
error: nil) { info in
let vc = info.instance() as UIViewController
let invocation = info.originalInvocation()
var ret = Int(self.allowRotation ? UIInterfaceOrientationMask.AllButUpsideDown.rawValue :
UIInterfaceOrientationMask.Portrait.rawValue)
invocation.setReturnValue(&ret)
}
}