手动检测屏幕横向旋转

11

我正在开发一个基于UITabBarController和UIViewController的iPhone应用程序,每个页面都有一个对应的视图控制器。该应用程序仅支持竖屏模式运行,因此每个视图控制器和应用委托都需要添加以下代码:

- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

在一个视图控制器中,当iPhone旋转到左横向时,我想弹出一个UIImageView。该图像的设计看起来是横向的,但宽度和高度为320x460(因此是纵向的)。

如何/应该手动检测这种类型的旋转,仅在此特定视图控制器中,在不对整个视图进行自动旋转的情况下?

Thomas

更新:

谢谢!我在viewDidLoad中添加了以下监听器:

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

didRotate方法看起来像这样:

- (void) didRotate:(NSNotification *)notification

    {   
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

        if (orientation == UIDeviceOrientationLandscapeLeft)
        {
            //your code here

        }
    }
2个回答

20

我在一个旧项目中需要这个 - 希望它仍然有效...

1)注册通知:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(detectOrientation)
                                             name:UIDeviceOrientationDidChangeNotification
                                           object:nil]; 

2)然后您可以根据更改进行旋转测试:

-(void) detectOrientation {
    if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
        ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {
        [self doLandscapeThings];
    } else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
        [self doPortraitThings];
    }   
}

希望能帮到你!


3
在viewDidLoad中添加了该监听器:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:)name:UIDeviceOrientationDidChangeNotification object:nil];didRotate方法如下:
  • (void) didRotate:(NSNotification *)notification { UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationLandscapeLeft) { //在这里编写你的代码 } }
- Thomas Joos
1
小改进,使用常量UIDeviceOrientationDidChangeNotification而不是其字符串值(即@"UIDeviceOrientationDidChangeNotification")。 - David Snabel-Caunt

2
更好的代码如下,使用Comic Sans字体。他的代码不总是能正确触发(在我的测试中只有80%的成功率)。
-(void) detectOrientation {
    if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
        [self setupForLandscape];
    } else if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
        [self setupForPortrait];
    } 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接