在iPad上没有完美的方法来检测设备方向?

时间:2011-03-02 22:00:56

标签: iphone objective-c cocoa-touch

编辑:给定的答案适用于设备,但要注意它在模拟器上失败。

当我的iPad启动时,我会在屏幕中间显示一个加载标签。我设置了autoresizingMask,以便在方向更改时重新定位。

当应用程序启动时,标签的文本会发生变化,因此我想根据新的长度重新标记标签。但是,以下代码不能正确地标记标签:

- (void) setLabelText:(NSString*)text {
  CGSize maximumLabelSize = CGSizeMake(500,20);
  CGSize expectedLabelSize = [text sizeWithFont:loadingLabel.font
                              constrainedToSize:maximumLabelSize
                                  lineBreakMode:loadingLabel.lineBreakMode];
  loadingLabel.frame = CGRectMake(self.view.frame.size.width/2-expectedLabelSize.width/2,
                                  loadingLabel.frame.origin.y, 
                                  expectedLabelSize.width, 
                                  loadingLabel.frame.size.height);
  loadingLabel.text = text;
}

我还考虑检查[[UIDevice currentDevice]方向],如果iPad处于横向模式,那么我将使用self.view.frame.size.height来设置标签的xOrigin。

但是,如果设备面朝上或面朝下(而不是横向或纵向),则此方法失败。我的appDelegate中还有一个lastOrientation变量,它根据设备的最后已知方向记住应用程序是横向还是纵向,即使面朝上或面朝下。但是,在启动时,不一定要设置此变量。

我在这里找不到一些简单的解决方案,所以我可以调整大小并使我的标签居中?

编辑:我尝试根据发布的建议检查UIStatusBarOrientation,但它不起作用:

if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeLeft
    || [[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeRight) {
  NSLog(@"landscape");  
  width = self.view.frame.size.height;
} else {
  NSLog(@"portrait");   
}

这始终会在模拟器上记录至少在启动时的肖像。

2 个答案:

答案 0 :(得分:2)

检查[[UIApplication sharedApplication] statusBarOrientation]

答案 1 :(得分:0)

我找到了一个解决FaceUp方向问题的技巧!!!

延迟定向检查,直到应用程序开始运行,然后设置变量,视图大小等!!!

//CODE

- (void)viewDidLoad {

  [super viewDidLoad];

  //DELAY
  [NSTimer scheduledTimerWithTimeInterval:0.5 
                     target:self 
                     selector:@selector(delayedCheck) 
                     userInfo:nil 
                     repeats:NO];

}


-(void)delayedCheck{

  //DETERMINE ORIENTATION
  if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait ){
      FACING = @"PU";
  }
  if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown ){
      FACING = @"PD";
  }
  if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft ){
      FACING = @"LL";
  }
  if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight ){
      FACING = @"LR";
  } 
  //DETERMINE ORIENTATION

  //START
  [self setStuff];
  //START

}


-(void)setStuff{

  if( FACING == @"PU" ){
          //logic for Portrait
  }
  else
  if( FACING == @"PD" ){
          //logic for PortraitUpsideDown
  }
  else{ 
  if( FACING == @"LL"){
          //logic for LandscapeLeft
  }
  else
  if( FACING == @"LR" ){
          //logic for LandscapeRight
  }

}

//CODE

您可以在'setStuff'函数中添加子视图,位置元素等......最初取决于方向的任何内容!!!

:d

-Chris Allinson