加速计是整个IOS屏幕旋转的基础,依赖加速计,设备才可以判断出当前的设备方向,IOS系统共定义了以下七种设备方向:
{
typedef NS_ENUM(NSInteger, UIDeviceOrientation) {
UIDeviceOrientationUnknown,
UIDeviceOrientationPortrait, // Device oriented vertically, home button on the bottom
UIDeviceOrientationPortraitUpsideDown, // Device oriented vertically, home button on the top
UIDeviceOrientationLandscapeLeft, // Device oriented horizontally, home button on the right
UIDeviceOrientationLandscapeRight, // Device oriented horizontally, home button on the left
UIDeviceOrientationFaceUp, // Device oriented flat, face up
UIDeviceOrientationFaceDown // Device oriented flat, face down
} __TVOS_PROHIBITED;
}
四种界面方向:
{
typedef NS_ENUM(NSInteger, UIInterfaceOrientation) {
UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft
} __TVOS_PROHIBITED;
}
解决的问题是:实现横向可旋转屏幕
解决方法如下:
实现方式一:
当加速计检测到方向变化的时候,会发出通知,我们通过注册观察者,来获取屏幕旋转更新信息。
注册代码如下:
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doRotate:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
监听到旋转屏幕时执行相应的方法:
{
- (void)doRotate:(NSNotification*)notification
{
//监听到需要旋转时,先把虚拟键盘关掉,不然虚拟键盘夺取了焦点而旋转
[[UIApplication sharedApplication].keyWindow endEditing:YES];
//do something
}
}
注意:若旋转时虚拟键盘正在开启,会获取焦点,或导致本该旋转的界面没有旋转,因此可以先关闭掉虚拟键盘再旋转。
实现方式二:
借助生命周期方法:
viewDidDisappear:弹出的界面消失时,记录其方向
viewWillAppear:当再次出现时,与之前纪录的方向进行比较,若不同则进行相应的角度旋转,否则不旋转。
网友评论