iOS:检测屏幕旋转,但是阻止它实际发生?

时间:2013-07-25 22:32:18

标签: ios mobile uiview

有没有办法检测屏幕即将旋转,还能防止这种旋转发生?本质上,我正在尝试实现一个类似于内置相机应用程序的界面,当设备从纵向移动到横向时控制对象在其中旋转(反之亦然),但子视图的布局实际上并没有改变。

我可以通过以下方式获得有关设备方向更改的通知:

[[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(deviceOrientationDidChange:)
    name:UIDeviceOrientationDidChangeNotification
    object:nil];

我可以通过将肖像作为唯一支持的方向来完全防止轮换,但如果我这样做,UIDeviceOrientationDidChangeNotification将根本不会触发。

我有办法拿我的蛋糕吃吗?

谢谢,

一个。 Stew Dent

1 个答案:

答案 0 :(得分:0)

您仍然可以使应用程序仅支持纵向,防止旋转,并使用加速度计捕捉旋转动作。

以下是执行此操作的一些代码:

头文件:

@interface MyController : UIViewController <UIAccelerometerDelegate>

@property(nonatomic, assign) UIInterfaceOrientation interfaceOrientation;

@end

在实施档案中:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration*)acceleration;
{
    CGFloat x = -[acceleration x];
    CGFloat y = [acceleration y];
    CGFloat angle = atan2(y, x);

    if ( angle >= -2.25f && angle <= -0.25f )
    {
        self.interfaceOrientation = UIInterfaceOrientationPortrait;
    }
    else if ( angle >= -1.75f && angle <= 0.75f )
    {
        self.interfaceOrientation = UIInterfaceOrientationLandscapeRight;
    }
    else if( angle >= 0.75f && angle <= 2.25f )
    {
        self.interfaceOrientation = UIInterfaceOrientationPortraitUpsideDown;
    }
    else if ( angle <= -2.25f || angle >= 2.25f )
    {
        self.interfaceOrientation = UIInterfaceOrientationLandscapeLeft;
    }
}

请记住在某处取消加速度计,例如在viewWillDisappear:

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIAccelerometer sharedAccelerometer] setDelegate:nil];

}

如果有效,请提供一些反馈意见。