一、判断横竖屏
UIInterfaceOrientation是iOS8之后使用的设备方向属性,在之前可以使用statusBarOrientation来设置和获取设备朝向。
iPhone/iPa的Home键盘是固定位置的,判断设备朝向可根据Home键位置来判断。
Home键在正下方,正向竖屏
Home键在正上方,反向竖屏
Home键在正左方,横屏模式
Home键在正右方,横屏模式
faceUp
faceDown
二、UIInterfaceOrientation
UIInterfaceOrientationUnknown
设备的朝向不能确定。
UIInterfaceOrientationPortrait
该设备处于竖屏模式,设备保持直立,底部的Home键。
UIInterfaceOrientationPortraitUpsideDown
该设备处于竖屏模式,但上下颠倒,设备保持直立,顶部的Home键。
UIInterfaceOrientationLandscapeLeft
设备处于横向模式,设备保持直立,右侧Home键。
UIInterfaceOrientationLandscapeRight
该设备处于横向模式,设备保持直立,左侧Home键。
UIInterfaceOrientation和statusBarOrientation是一一对应的。
三、横竖屏设置
1、设置项目设备支持的转屏
在项目里设置:
或者在plist文件中设置:
项目中设置的会自动添加到plist文件配置中。
2、设置个别界面的转屏
通过复写一下方法进行个别界面的转屏设置
//当前viewcontroller是否支持转屏
- (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0);
//当前viewcontroller支持哪些转屏方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations;
//当前viewcontroller默认的屏幕方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation;
比如我们iPad的某个界面只支持竖屏显示,这样就可以了:
- (BOOL)shouldAutorotate {
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationPortrait;
}
其他界面同理。
3、设备转屏监听
UIDeviceOrientationDidChangeNotification 和 UIApplicationDidChangeStatusBarFrameNotification
网上有说UIDeviceOrientationDidChangeNotification只监听横竖屏,我试了一下每个方向都是能被监听的,并不是只监听横竖屏。
UIApplicationDidChangeStatusBarFrameNotification这个监听是当屏幕上图像确实是转了,才会触发通知。
如果要做屏幕的监听建议用UIDeviceOrientationDidChangeNotification。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
- (void)deviceOrientationDidChange:(NSNotification *)notic {
UIDeviceOrientation orient = [UIDevice currentDevice].orientation
...
}