Runtime解决屏幕旋转问题

前言

大家或许在iOS程序开发中经常遇到屏幕旋转问题,比如说希望指定的页面进行不同的屏幕旋转,但由于系统提供的方法是导航控制器的全局方法,无法随意的达到这种需求。一般的解决方案是继承UINavrgationViewController,重写该类的相关方法,这样虽然也能解决问题,但是在重写的过程中至少产生两个多余的文件和不少的代码,这显然不是我们想要的。下面就使用一种较底层的方法解决这个问题。

基本原理

动态的改变UINavrgationViewController的全局方法,将我们自己重写的supportedInterfaceOrientationsshouldAutorotate方法和导航控制器对象的方法进行替换即可。

准备工作

配置项目支持方向

代码实现

将下面的方法写在所有视图控制器的父类的viewDidLoad方法中,即可完成屏幕旋转方向的配置。

//获取当前视图控制器的旋转支持方法
Method selfMtihod = class_getInstanceMethod([self class], @selector(shouldAutorotate));
//获取当前导航控制器的旋转支持方法
Method navr = class_getInstanceMethod([self.navigationController class], @selector(shouldAutorotate));
//交换方法
method_exchangeImplementations(selfMtihod, navr);

//以下同理
Method selfOrientation = class_getInstanceMethod([self class], @selector(supportedInterfaceOrientations));
Method navrOrientation = class_getInstanceMethod([self.navigationController class], @selector(supportedInterfaceOrientations));
method_exchangeImplementations(selfOrientation, navrOrientation);

使用方法

  • 在上面的父类中重写supportedInterfaceOrientationsshouldAutorotate,表示默认的屏幕旋转相关属性。
  • 在之后的每个该试图控制器的子类中,可重写supportedInterfaceOrientationsshouldAutorotate方法,即可完成指定视图控制器方向的需求。
posted @ 2016-09-17 10:50  Silktree  阅读(301)  评论(0编辑  收藏  举报