工作中遇到這樣一個(gè)需求官撼,在當(dāng)手機(jī)投影到airDrop設(shè)備時(shí)要跟投影的設(shè)備屏幕方向保持一致策彤,用戶鎖定時(shí)也要隨投影設(shè)備旋轉(zhuǎn)靴庆,用戶沒有鎖定時(shí)只隨投影設(shè)備旋轉(zhuǎn)褪贵,而不能隨手機(jī)旋轉(zhuǎn)掂之。
花了一上午時(shí)間,搞定了這個(gè)問(wèn)題脆丁,發(fā)現(xiàn)網(wǎng)上的資料都是iOS8之前的世舰,很多都是過(guò)時(shí)的,或都不夠全面偎快,現(xiàn)在總結(jié)如下:
1.beginGeneratingDeviceOrientationNotifications endGeneratingDeviceOrientationNotifications
這兩個(gè)是控制屏幕旋轉(zhuǎn)的通知冯乘,通知在手機(jī)轉(zhuǎn)動(dòng)時(shí)觸發(fā),觸發(fā)后會(huì)執(zhí)行下面的方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window? NS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED;
-(BOOL)shouldAutorotate
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
其中后兩個(gè)是寫在VC中的晒夹,只能在present出來(lái)的VC才能生效裆馒,第一個(gè)是寫在AppDelegate中,全局生效丐怯。
在屏幕要旋轉(zhuǎn)后會(huì)執(zhí)行
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator NS_AVAILABLE_IOS(8_0);
只要屏幕轉(zhuǎn)動(dòng)都會(huì)觸發(fā)喷好,就算手機(jī)沒有轉(zhuǎn)動(dòng)強(qiáng)制橫豎屏有屏幕有轉(zhuǎn)動(dòng)也會(huì)觸發(fā)。
2.關(guān)于方向的幾個(gè)枚舉
UIInterfaceOrientationMask:支持的方向读跷。
UIInterfaceOrientation:手機(jī)界面的方向梗搅。
UIDeviceOrientation:設(shè)備當(dāng)前的方向,這個(gè)是個(gè)坑,用戶鎖定了后永遠(yuǎn)是Unknown,而且沒鎖定的情況下也不是很準(zhǔn)確无切。
這幾個(gè)枚舉在不注意的情況下可能會(huì)搞混荡短,注意下就行
3.強(qiáng)制橫豎屏
網(wǎng)上的方法有好幾種,最后發(fā)現(xiàn)還是下面這個(gè)有用哆键,其他的都不行掘托。
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
注意這個(gè)方法執(zhí)行前要保證supportedInterfaceOrientations一定要包括要強(qiáng)制旋轉(zhuǎn)的方向,不然會(huì)閃退籍嘹,要想保證不出現(xiàn)閃退可以supportedInterfaceOrientations設(shè)成ALL