iOS的TNV架构下,实现TabBar不旋转,其他页可选旋转

TNV架构下,部分旋转这个功能,实现起来比较蛋疼,给一个目前的方法。

1、自定义TabBar:

extension C4MVTTabBarController: UITabBarControllerDelegate {
    func tabBarControllerSupportedInterfaceOrientations(_ tabBarController: UITabBarController) -> UIInterfaceOrientationMask {
        return selectedViewController?.supportedInterfaceOrientations ?? .all
    }

    func tabBarControllerPreferredInterfaceOrientationForPresentation(_ tabBarController: UITabBarController) -> UIInterfaceOrientation {
        return selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }
}

并且记得设置delegate

2、自定义NavigationController

class C4MVTNavigationController: UINavigationController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return self.visibleViewController?.supportedInterfaceOrientations ?? .portrait
    }

    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return self.visibleViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }
}

 

3、自定义ViewController

class C4MVTBaseController: UIViewController {

    var needRotate: Bool {
        return false
    }

    override var shouldAutorotate: Bool {
        return needRotate ? true : false
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return needRotate ? .all : .portrait
    }

    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }

    ////在返回的时候 (具体怎么判断和你的页面push还是模态present有关)
    if (needRotate) {
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
    }

}

最后退出时强制设置为竖屏 一定不要忘记,否则会有个小bug

 

Leave a Reply

Your email address will not be published. Required fields are marked *