7

在没有 XIB 文件的loadView方法中(在 中)计算视图大小的最佳实践是什么?UIViewController

这是我的解决方案:

- (void)loadView {

  //Calculate Screensize
  BOOL statusBarHidden = [[UIApplication sharedApplication] isStatusBarHidden ];
  BOOL navigationBarHidden = [self.navigationController isNavigationBarHidden];
  BOOL tabBarHidden = [self.tabBarController.tabBar isHidden];

  CGRect frame = [[UIScreen mainScreen] bounds];

  if (!statusBarHidden) {
    frame.size.height -= [[UIApplication sharedApplication] statusBarFrame].size.height; 
  }
  if (!navigationBarHidden) {
    frame.size.height -= self.navigationController.navigationBar.frame.size.height; 
  }
  if (!tabBarHidden) {
    frame.size.height -= self.tabBarController.tabBar.frame.size.height; 
  }

  UIView *v = [[UIView alloc] initWithFrame: frame];
  [v setBackgroundColor: [UIColor whiteColor] ];
  [v setAutoresizingMask: UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];
  [self setView: v ];
  [v release];      
}

这段代码可以吗,还是我应该编辑一些东西?

4

3 回答 3

6

文档建议使用[[UIScreen mainScreen] applicationFrame]在没有状态栏的情况下获取屏幕边界

于 2012-02-06T10:45:40.873 回答
1

因此,对于任何想了解最佳实践示例的人来说:

#pragma mark -
#pragma mark LoadView Methods
- (void)loadView {

  //Calculate Screensize
  BOOL statusBarHidden = [[UIApplication sharedApplication] isStatusBarHidden ];
  BOOL navigationBarHidden = [self.navigationController isNavigationBarHidden];
  BOOL tabBarHidden = [self.tabBarController.tabBar isHidden];
  BOOL toolBarHidden = [self.navigationController isToolbarHidden];

  CGRect frame = [[UIScreen mainScreen] applicationFrame];

  //check if you should rotate the view, e.g. change width and height of the frame
  BOOL rotate = NO;
  if ( UIInterfaceOrientationIsLandscape( [UIApplication sharedApplication].statusBarOrientation ) ) {
    if (frame.size.width < frame.size.height) {
      rotate = YES;
    }
  }

  if ( UIInterfaceOrientationIsPortrait( [UIApplication sharedApplication].statusBarOrientation ) ) {
    if (frame.size.width > frame.size.height) {
      rotate = YES;
    }
  }

  if (rotate) {
    CGFloat tmp = frame.size.height;
    frame.size.height = frame.size.width;
    frame.size.width = tmp;
  }


  if (statusBarHidden) {
    frame.size.height -= [[UIApplication sharedApplication] statusBarFrame].size.height;
  }
  if (!navigationBarHidden) {
    frame.size.height -= self.navigationController.navigationBar.frame.size.height;
  }
  if (!tabBarHidden) {
    frame.size.height -= self.tabBarController.tabBar.frame.size.height;
  }
  if (!toolBarHidden) {
    frame.size.height -= self.navigationController.toolbar.frame.size.height;
  }

  UIView *v = [[UIView alloc] initWithFrame: frame];
  v.backgroundColor = [UIColor whiteColor];
  v.autoresizingMask  = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

  self.view = v;
  [v release]; //depends on your ARC configuration
}
于 2012-10-25T12:34:25.743 回答
0

您正在调整高度取决于状态栏和导航栏。但是您没有对视图的原点做任何事情。

于 2012-02-06T09:56:02.020 回答