在没有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];
}
这个代码可以吗?还是应该编辑一些内容?
文档建议使用[[UIScreen mainScreen] applicationFrame]
在没有状态栏的情况下获得屏幕边界
因此,对于任何想了解最佳实践的人来说,例如:
#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
}
您正在根据状态栏和导航栏调整高度。。但是你没有对这个观点的起源做任何事情。