我的应用程序可以在两个方向(纵向和横向)下运行,但其中一个屏幕被锁定为纵向模式。但我必须为该特定屏幕在“旋转”变量中设置一个值。但我没有找到方向。 所以我想找到方向。 我使用下面的代码将屏幕锁定为纵向模式,它会起作用。
- (UIInterfaceOrientationMask) supportedInterfaceOrientations {
[super supportedInterfaceOrientations];
return UIInterfaceOrientationMaskPortrait;
}
我正在使用下面的方法来检测方向,但这不会被调用。
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
{
NSLog(@"UIInterfaceOrientationPortrait");
}
else
{
NSLog(@"UIInterfaceOrientationland");
}
}
如果屏幕锁定在纵向模式下,您可以检测方向。最简单的方法是“CoreMotion”。代码片段如下。
1-) 首先,您应该将 CoreMotion freamework 添加到 Build Settings
2-) 导入 CoreMotion freework
#import <CoreMotion/CoreMotion.h>
3-) 添加属性如下。
@interface BaseGeneralViewController (){
UIInterfaceOrientation orientationLast, orientationAfterProcess;
CMMotionManager *motionManager;
UIInterfaceOrientation orientationNew;
}
4-) 我们创建了初始化方法
- (void)initializeMotionManager{
motionManager = [[CMMotionManager alloc] init];
motionManager.accelerometerUpdateInterval = .2;
motionManager.gyroUpdateInterval = .2;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
if (!error) {
[self outputAccelerationData:accelerometerData.acceleration];
}
else{
NSLog(@"%@", error);
}
}];
}
5-) 声明outputAccelerationData方法
- (void)outputAccelerationData:(CMAcceleration)acceleration{
if (acceleration.x >= 0.75 && orientationLast != UIInterfaceOrientationLandscapeLeft) {
orientationNew = UIInterfaceOrientationLandscapeLeft;
[self callQRCodePayment:UIDeviceOrientationLandscapeRight];
}
else if (acceleration.x <= -0.75 && orientationLast != UIInterfaceOrientationLandscapeRight) {
orientationNew = UIInterfaceOrientationLandscapeRight;
[self callQRCodePayment:UIDeviceOrientationLandscapeLeft];
}
else if (acceleration.y <= -0.75) {
//orientationNew = UIInterfaceOrientationPortrait;
//NSLog(@"Portrait");
}
else if (acceleration.y >= 0.75) {
//orientationNew = UIInterfaceOrientationPortraitUpsideDown;
}
else {
// Consider same as last time
return;
}
if (orientationNew == orientationLast)
return;
orientationLast = orientationNew;
}
6-) 在viewDidload中调用初始化方法
- (void)viewDidLoad
{
[super viewDidLoad];
[self initializeMotionManager];
}
您可以查看详细帖子更改方向
这里有检测方向的方法
UIDeviceOrientationIsLandscape
和 UIDeviceOrientationIsPortrait
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
// code here for landscape orientation
}
// And
if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
{
// code here for Portrait orientation
}