最近突然被告知要適配橫屏,當然最麻煩的是你還不知道iOS工程到底允不允許橫屏,或許說的有點繞口,待會兒看會細說的。其實很想感慨一句:各種奇葩的合理不合理的需求都會遇到的,做爲程序員能做的只有打好基礎才能應對各種情況。
先說幾個API吧,獲取iOS項目工程自帶的plist文件:
NSDictionary *plist = [[NSBundle mainBundle] infoDictionary];
然後你可以在這裏獲得你的項目配置,有興趣的可以自己看看這個字典裏有哪些key,跟今天我要說的有關的是這個:UISupportedInterfaceOrientations
NSArray *arryplist = plist[@"UISupportedInterfaceOrientations"];
你獲取的這個arryplist裏面的元素是你在項目配置中設置的允許這個app支持哪些方向是直立的、向左橫屏、向右橫屏、顛倒。最多會有這四個元素(因爲工程配置中最多隻支持這個四個方向的):UIInterfaceOrientationPortrait、UIInterfaceOrientationPortraitUpsideDown、UIInterfaceOrientationLandscapeLeft、UIInterfaceOrientationLandscapeRight。
通過以上兩行代碼你可以獲取到這個APP支持哪些方向的。
還要在說個小技巧,你可以通過監聽這個通知實時獲取到屏幕方向改變的消息:UIDeviceOrientationDidChangeNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeFrame) name:UIDeviceOrientationDidChangeNotification object:nil];
不要忘了還要移除通知
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}
這樣當手機屏幕方向改變時候你就可以知道了。
今天最後再說個API通過這個方法你可以獲取到當前手機是橫屏、還是豎屏、其他位置狀態:
[UIDevice currentDevice].orientation
你獲取到的值是個枚舉類型,有這些值:
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;
配合以上三個技巧,你可以進行橫豎屏的適配:
- (void)changeFrame {
CGRect rect = [UIScreen mainScreen].bounds;
CGFloat width = rect.size.width;
CGFloat height = rect.size.height;
NSDictionary *plist = [[NSBundle mainBundle] infoDictionary];
NSArray *arryplist = plist[@"UISupportedInterfaceOrientations"];
switch ([UIDevice currentDevice].orientation) {
case UIDeviceOrientationPortrait://這是豎屏
for (NSString *stringplist in arryplist) {
if ([stringplist isEqualToString:@"UIInterfaceOrientationPortrait"]) { //判斷這個APP是否允許豎屏,允許了再改變frame
}
}
break;
case UIDeviceOrientationLandscapeLeft:
for (NSString *stringplist in arryplist) {
if ([stringplist isEqualToString:@"UIInterfaceOrientationLandscapeLeft"]) {
}
}
}
break;
case UIDeviceOrientationLandscapeRight:
for (NSString *stringplist in arryplist) {
if ([stringplist isEqualToString:@"UIInterfaceOrientationLandscapeRight"]) {
}
}
break;
default:
break;
}
}