当前位置: 移动技术网 > 移动技术>移动开发>Android > 详解Android中Runtime解决屏幕旋转问题(推荐)

详解Android中Runtime解决屏幕旋转问题(推荐)

2019年07月24日  | 移动技术网移动技术  | 我要评论

前言

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

基本原理

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

准备工作

配置项目支持方向

代码实现

将下面的方法写在所有视图控制器的父类的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);

使用方法

在上面的父类中重写supportedinterfaceorientations、shouldautorotate,表示默认的屏幕旋转相关属性。

在之后的每个该试图控制器的子类中,可重写supportedinterfaceorientations、shouldautorotate方法,即可完成指定视图控制器方向的需求。

以上所述是小编给大家介绍的runtime解决屏幕旋转问题的方法详解,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网