導(dǎo)入 :
#import <CoreMotion/CoreMotion.h>
增加屬性:
@property (strong, nonatomic) CMMotionManager *motionManager;
@property (assign, nonatomic) BOOL isLandScape;
初始化:
self.isLandScape = NO;
[self initMotionManager];
在真機關(guān)閉屏幕旋轉(zhuǎn)功能時如何去判斷屏幕方向:
-- (void)initMotionManager
{
if (_motionManager == nil)
{
_motionManager = [[CMMotionManager alloc] init];
}
// 提供設(shè)備運動數(shù)據(jù)到指定的時間間隔
_motionManager.deviceMotionUpdateInterval = .3;
// _motionManager.accelerometerAvailable
if (_motionManager.deviceMotionAvailable)
{
// 確定是否使用任何可用的態(tài)度參考幀來決定設(shè)備的運動是否可用
// 啟動設(shè)備的運動更新,通過給定的隊列向給定的處理程序提供數(shù)據(jù)。
[_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion *motion, NSError *error)
{
if (self.wmPlayer && self.wmPlayer.superview)
{
[self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
}
}];
}
else
{
[self setMotionManager:nil];
}
}
- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion
{
double x = deviceMotion.gravity.x;
double y = deviceMotion.gravity.y;
if (fabs(y) >= fabs(x))
{
//NSLog(@"豎屏");
if (self.isLandScape == YES)
{
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
//這句話是防止手動先把設(shè)備置為豎屏,導(dǎo)致下面的語句失效.
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
self.isLandScape = NO;
[self toCell];
}
}
else
{
//NSLog(@"橫屏");
if (self.isLandScape == NO)
{
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
// 這句話是防止手動先把設(shè)備置為橫屏,導(dǎo)致下面的語句失效.
if(x > 0)
{
// 左邊在上
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeRight] forKey:@"orientation"];
[self toFullScreenWithInterfaceOrientation:UIInterfaceOrientationLandscapeLeft];
}
else
{
// 右邊在上
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
[self toFullScreenWithInterfaceOrientation:UIInterfaceOrientationLandscapeRight];
}
self.isLandScape = YES;
}
}
}
強烈推薦:超簡單?。?! iOS設(shè)置狀態(tài)欄、導(dǎo)航欄按鈕、標題、顏色、透明度,偏移等
https://github.com/wangrui460/WRNavigationBar
https://github.com/wangrui460/WRNavigationBar_swift
歡迎關(guān)注我的微博:wangrui460