【问题标题】:iPad Orientation Checking UIView Class?iPad 方向检查 UIView 类?
【发布时间】:2011-10-15 18:03:50
【问题描述】:

我有一个UIView 类,我将它添加到我的主UIViewController 中,我需要在应用程序启动时检查设备(iPad)的方向,在viewDidLoad 方法中。但是因为类是UIView(不是UIViewController),所以我不能使用willAnimateRotationToInterfaceOrientation等方法。

所以我尝试在我的UIView 课程中使用它:

if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) ||
    ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {

但是,使用一些断点进行测试,无论方向是什么,of 语句都不会被调用,它的跳过正确地通过了它。那么你建议我做些什么来克服这个问题?

我需要从 UIView 类中检测方向。

谢谢。

【问题讨论】:

    标签: objective-c ipad uiview orientation


    【解决方案1】:

    您将支票放在哪里?该位置可以很容易地解释为什么它没有被调用。要获取旋转信息,您可以register for a notification,或者让您的视图控制器在您的视图中调用一个方法。后者的示例代码:

    // ViewController.m
    - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
        [self.customView willRotateToOrientation:toInterfaceOrientation];
    }
    
    // CustomView.m
    - (void)willRotateToOrientation:(UIInterfaceOrientation)newOrientation {
        // Handle rotation
    }
    

    视图控制器方法是您覆盖的方法;视图的方法应该在标题中声明。

    更新: 或者,您可以在控制器的 `viewWillAppear' 中找到旋转:

    // ViewController.m
    - (void)viewWillAppear {
        [self.customView willRotateToOrientation:[[UIDevice currentDevice] orientation];
    }
    

    您视图中的方法将被相应地调用。

    【讨论】:

    • 我试过这个,麻烦的是,willRotateToInterfaceOrientation 似乎在 'viewDidLoad' 之后被调用,这意味着这是没用的。因此,此方法仅在旋转后旋转时有效,而不是在应用加载后立即有效。
    • 您可以在viewWillAppear 中找到方向,然后调用视图——查看更新的答案。
    • 原来指向另一个答案的链接运行良好。 [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 让我的 OP 中的 if 语句很有魅力。
    【解决方案2】:

    您可以做的一件事是从NSNotificationCenter 注册方向通知:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    ...
    
    - (void)orientationChanged:(NSNotification *)notification
    {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        // do things
    }
    

    然而,这不是最理想的,因为当应用程序启动时 iPad 可能平放在桌子上,然后你会得到 UIDeviceOrientationUnknown。到过这里,做到了……

    我最终做了一个这样的简单检查:

    BOOL landscape = self.bounds.size.width > self.bounds.size.height;
    if (landscape)
        // landscape stuff
    else
        // portrait stuff
    

    但在我的例子中,视图在旋转时改变了纵横比。如果您也是这种情况,它应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多