我已經看到幾個類似的問題,但沒有解決我的具體需求。我希望能夠編寫一個通用的幫助器方法,該方法返回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中放置視圖的位置。否則,你仍然可能在導航欄下結束。 –