我已经看到几个类似的问题,但没有解决我的具体需求。我希望能够编写一个通用的帮助器方法,该方法返回UIView的最大可用帧大小,同时考虑应用程序是否具有状态栏,导航栏和/或选项卡栏的任意组合,因为我发现自己正在执行此操作时间。以编程方式确定UIView的最大可用帧大小
方法的定义是作为UIScreen的延伸:
+ (CGRect) maximumUsableFrame;
获取尺寸带或不带状态栏可以从
[UIScreen mainScreen].applicationFrame
属性来得到的,但我不能图找出一种确定是否存在导航栏或标签栏的方式。我想过在应用程序委托中维护一些全局标志,但这看起来非常笨重,并且停止了代码的泛型和可重用。我也考虑过传递一个UIView作为参数,获取视图的窗口,然后是rootViewController,然后看看是否设置了导航控制器属性。如果是,则检查导航控制器是否隐藏。如果你问我,这一切都很笨重。
任何想法将不胜感激。
戴夫
编辑:万一从迦勒的回答结合的想法,这是使用的其他任何人:
// Extension to UIViewController to return the maxiumum usable frame size for a view
@implementation UIViewController (SCLibrary)
- (CGRect) maximumUsableFrame {
static CGFloat const kNavigationBarPortraitHeight = 44;
static CGFloat const kNavigationBarLandscapeHeight = 34;
static CGFloat const kToolBarHeight = 49;
// Start with the screen size minus the status bar if present
CGRect maxFrame = [UIScreen mainScreen].applicationFrame;
// If the orientation is landscape left or landscape right then swap the width and height
if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
CGFloat temp = maxFrame.size.height;
maxFrame.size.height = maxFrame.size.width;
maxFrame.size.width = temp;
}
// Take into account if there is a navigation bar present and visible (note that if the NavigationBar may
// not be visible at this stage in the view controller's lifecycle. If the NavigationBar is shown/hidden
// in the loadView then this provides an accurate result. If the NavigationBar is shown/hidden using the
// navigationController:willShowViewController: delegate method then this will not be accurate until the
// viewDidAppear method is called.
if (self.navigationController) {
if (self.navigationController.navigationBarHidden == NO) {
// Depending upon the orientation reduce the height accordingly
if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
maxFrame.size.height -= kNavigationBarLandscapeHeight;
}
else {
maxFrame.size.height -= kNavigationBarPortraitHeight;
}
}
}
// Take into account if there is a toolbar present and visible
if (self.tabBarController) {
if (!self.tabBarController.view.hidden) maxFrame.size.height -= kToolBarHeight;
}
return maxFrame;
}
如果导航栏和TabBar可见,你可以找到高这样说:'self.navigationController.navigationBar.frame.size.height;'和'self.tabBarController.tabBar.frame.size.height'。为什么称为kToolBarHeight的tabbar高度变量?=) – Alexander
根据你想如何使用它,至少在我的情况下,我也更新了navController的框架原点,所以我确切知道我可以在ViewController中放置视图的位置。否则,你仍然可能在导航栏下结束。 –