2013-01-17 27 views
14

如果我有一个指向UIViewController的指针,当它改变interfaceOrientation而不修改控制器的代码时,我可以得到通知吗?我可以观察UIViewController更改interfaceOrientation的时间吗?

是我最好的选择,检测设备方向的变化,然后看看UIViewController是否会旋转(d)?

+0

不确定问题是否仍然存在,但是您可以使用objc方法调试来将自己的代码添加到'UIViewController'代码中。这应该看起来像是用你自己的实现交换'-didRotateFromInterfaceOrientation:',它有一个调用你的方向改变的处理方法和一个原来的执行调用 – medvedNick

+0

@medvedNick这看起来很合理。我可以调用我的委托,然后调用原始实现。我可能会担心潜在的副作用。 –

回答

16

您可以使用NSNotificationCenter:

[[NSNotificationCenter defaultCenter] addObserver:self // put here the view controller which has to be notified 
             selector:@selector(orientationChanged:) 
              name:@"UIDeviceOrientationDidChangeNotification" 
              object:nil]; 
- (void)orientationChanged:(NSNotification *)notification{ 
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; 

    //do stuff 
    NSLog(@"Orientation changed");   
} 
+3

嗯。我想我不清楚。我想知道ViewController而不是设备的明显方向。换句话说,我的对象希望观察视图控制器以查看其方向,该方向可能与设备不同,并且在设备改变方向时可能不会改变。这个答案是我在问题的第二部分所暗示的一部分。 –

2

您可以使用您的UIViewController的willAnimateRotationToInterfaceOrientation:duration:方法,然后重新任何UIViews(或任何其他代码)横向或纵向。例如。

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { 
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) { 
    // change positions etc of any UIViews for Landscape 
    } else { 
    // change position etc for Portait 
    } 

    // forward the rotation to any child view controllers if required 
    [self.rootViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration]; 
} 
+1

不幸的是,这将意味着更改UIViewController的代码。这里我只有一个指向它的指针,并且想要观察它的行为。当“interfaceOrientation”返回不同的值时,我会真正想要做什么。 –

+0

注意:这在iOS 8中已弃用。http://stackoverflow.com/questions/25238620/ios-8-rotation-methods-deprecation-backwards-compatibility – jowie