How to get the height of the Navigation bar - ios

I am developing my first iPhone application. I am quite new to iOS. I am trying to get the height of the UI Navigation bar using the code below below the viewDidLoad method
float navBarHeight = self.navigationController.navigationBar.frame.size.height;
But the navBarHeight is returning 0. Not sure why that is.

Might be your using custom UIView for navigation or your hiding NavigationBar in your code i.e.,why it showing height is 0.If you set below code in your viewWillAppear you will get height of NavigationBar.
[self.navigationController setNavigationBarHidden:NO];

Try this extension (considering iPhone-X)
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}

Try :
print(self.navigationController?.navigationBar.frame.height)

Related

Swift: Moving a tab bar controller to top of view controller

Currently my tab bar controller is at the bottom of the view controller. I was wondering if there is a way to move it to the top of the view controller as I cant seem to find any documentation on it.
Swift 3
let rect = self.tabBar.frame;
self.tabBar.frame = rect.insetBy(dx: 0, dy: -view.frame.height + self.tabBar.frame.height + (self.navigationController?.navigationBar.frame.height)!)
Swift 5 | Xcode 11
Try overriding viewWillLayoutSubviews() in your class that extends UITabBarController and then put following:-
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tabBar.invalidateIntrinsicContentSize()
var tabSize: CGFloat = 44.0;
var orientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
if (orientation.isLandscape) {
tabSize = 32.0;
}
var tabFrame: CGRect = self.tabBar.frame;
tabFrame.size.height = tabSize;
tabFrame.origin.y = self.view.frame.origin.y;
self.tabBar.frame = tabFrame;
// Set the translucent property to false then back to true to
// force the UITabBar to reblur, otherwise part of the
// new frame will be completely transparent if we rotate
// from a landscape orientation to a portrait orientation.
self.tabBar.isTranslucent = false;
self.tabBar.isTranslucent = true;
}
Reference: https://stackoverflow.com/a/29580094/6117565
You can't change position on UITabbar. Read Apple documentation for tabbar.
If you want to set effect like tabbar on top of viewController then You can manage that by using one uiview of same size of tabbar and multiple uibuttons in that view which works as tabs. And set that view at top or any position at which you want to show tabbar. You have to manage viewcontrollers displays on button click and manage that view to every view controller. So it is very difficult task, so it is better to use default tabbarController provided by system.
You can try using UIViewController instead of UITabBarController and then place TabBar control on top in your view by constraints.
Another way is create your own tabbar. (:

Get frame height without navigation bar height and tab bar height in deeper view hierarchy

I have a ViewController (B) which is handled by a PageViewController which is inside another ViewController (A) and open it modal. I have centered the ViewController (B) exactly in the middle of the screen. This works fine.
But when I push the ViewController (A) from a NavigationController the frame of ViewController (B) is to big and extends below the NavigationBar and the TabBar. But I want it centered between the NavigationBar and the TabBar.
I know how I can get the height of the navbar and the tabbar so I could resize ViewController (B):
var topBar = self.navigationController?.navigationBar.frame.height
var bottomBar = self.tabBarController?.tabBar.frame.height
But this does not work deep down in the vier hierarchy in ViewController (B). self.navigationController and self.tabBarController are nil. So how can I get the height of the navbar and tabbar deeper down in the view hierarchy? Or do I just have to pass it down from one ViewController to another till I reach ViewController (B)? Or is there another more obvious way to center the view? Thanks.
(I have tried to post screenshots for better understanding but I miss the needed reputation points to post images, sorry)
Use this :
let height = UIApplication.sharedApplication().statusBarFrame.height +
self.navigationController!.navigationBar.frame.height
this support portrait and landscape state.
Swift 5
let height = UIApplication.shared.statusBarFrame.height +
self.navigationController!.navigationBar.frame.height
For UITabBar, this code work :
self.tabBarController?.tabBar.frame.height
For Swift 3
navBarHeight = (self.navigationController?.navigationBar.intrinsicContentSize.height)!
+ UIApplication.shared.statusBarFrame.height
As for iOS 13, since the statusBarFrame property of a UIApplication object was deprecated, one can use:
let statusBarHeight = navigationController?.view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
let navigationBarHeight = navigationController?.navigationBar.frame.height ?? 0
Now, it may seem that doesn't help you #OP since your navigationController is nil, but you could try to use view.window?.windowScene?.statusBarManager?.statusBarFrame.height for the statusBar height and figure out a way to find the navBar height as well? Hope that helps :)
iOS 13 solution:
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
return (window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
To call it you can just use: self.topbarHeight in viewController
Navigation bar height status bar height and tab bar height is always constant :
Navigation bar - 44pts
Status bar - 20pts
Tab bar - 49pts.
You can directly subtract these constants from view height:
self.view.frame.size.height- (44+20+49)

iOS 7 Status Bar Collides With NavigationBar

I have a view controller in my app that has a navigation bar dragged on it in the storyboard. It was working fine in the iOS 6 but in iOS 7 it look like this:
The status bar and the navigation bar should no collide with each other. I have seen a lot of such questions on the stack overflow but they didn't of much help to me.
Some questions say that i should use this "self.edgesForExtendedLayout = UIRectEdgeNone;" but it didn't work. Some say i should remove the navigation bar and embed it inside the navigation controller that i cannot do due to the way my program is implemented. Some solutions suggests to use the view bounds and all but it didn't work for me as well.
What is the one thing that can help me resolve this issue. Thanks in advance!
UPDATE: I have embedded the view controller inside a uinavigation controller. Removed the navigation bar that was earlier manually added in it. Now it looks ok in the storyboard but when i run it, it shows the following:
It is showing text from another view controller that is currently behind it that is its parent view controller. Means its transparent now. Can anyone point out what i am doing wrong?
The latest version of the iOS has brought many visual changes and from a developer's point of view, the navigation and status bar are two noticeable changes.
The status bar is now transparent and navigation bar behind it shows through. The navigation bar image can even be extended behind the status bar.
First of all, if you are a beginner and have just started iOS development and are confused the way status bar and navigation bar is working, you can simply go through a blog post HERE that i found very useful. It has all the information related to navigation and status bar in iOS 7.
Now coming to the answer of your question. First of all i can see two different problems. One is that your status bar and navigation bar are both kind of colliding with each other as shown by you in the question with an image.
PROBLEM: Well the problem is that your have earlier dragged a navigation bar in your view controller which was working in iOS 6 correctly but with the arrival of iOS 7 SDK, this approach is resulting in status bar and navigation bar overlapping with each other.
SOLUTION to First Problem: You can either use UIBarPositionTopAttached or you can use view bounds and frames, i can also suggest and link you to Apple's documentation and bla bla bla but that would take some time for you to solve the issue.
The best and the most easiest way to solve this issue is to just embed your view controller inside a navigation controller and thats it. You can do it by just selecting the view controller and going to Editor > Embed In > Navigation Controller. (If there is any content on your old navigation bar, you can first drag it down, embed the view controller in navigation controller and then move the bar buttons on the new navigation bar and then delete the old navigation bar)
SOLUTION to Second Problem: This solution is for your specific question that you have mentioned in the update and is not for the general public reading this. As you can see that navigation and status bar is not visible and a transparent area is showing the parent view controller. I am not really use why you are facing this issue but most probably because of some third party library like ECSlidingView or any other is involved. You can select this view controller in your storyboard and set the background color of the view to be the same as your navigation bar. This will stop showing the parent view controller behind and your navigation bar and status bar will start showing. Now you can cover the rest of your view controller with text view or what ever your are using in it.
Hope this helps!
The navigation bar is too close to the status bar because starting in iOS 7, the status bar is more of an overlay over the whole view controller's view. Since your navigation bar is at (0, 0), the status bar will show on top of the navigation bar. To solve this, simply move the navigation bar down (or, as others have said), create a constraint between the navigation bar and the topLayoutGuide.
When you do that, you will see that there is now a 20 point gap between the navigation bar and the top of the screen. That's because you just moved the navigation bar down 20 points. "But UINavigationController can do it right!" Absolutely, and it does so by implementing UIBarPositioningDelegate on your view controller. This is a one-method protocol that should be implemented like this:
- (UIBarPosition)positionForBar:(id<UIBarPositioning>)bar {
return UIBarPositionTopAttached;
}
After adding your view controller as the delegate for the navigation bar, you'll notice the navigation bar is still shifted down 20 points, but its background will extend up underneath the status bar, just like in UINavigationController.
Another thing you're seeing is that the navigation bar is translucent, meaning anything underneath the navigation bar will be visible to some extent. The translucent property on UINavigationBar is set to YES by default on iOS 7. Before iOS 7, the default was NO.
you can simply do this:
1) add a constrain between the Navigation Bar and Top Layout Guide (select navigationBar, hold ctrl key and go to Bottom Layout Guide, unhold ctrl key)
2) select vertical spacing:
3) set constant to 0:
Result:
UPDATE
In your AppDelegate file you can add this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
// Prevent Navigationbar to cover the view
UINavigationBar.appearance().translucent = false
}
I suggest you in your viewDidLoad method you try:
self.navigationController.navigationBar.translucent = NO;
(by default it is yes now)
https://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationBar_Class/Reference/UINavigationBar.html#//apple_ref/occ/instp/UINavigationBar/translucent
This works for me i hope you also have same luck :).
Add below code in your view.
-(void) viewDidLayoutSubviews
{
CGRect tmpFram = self.navigationController.navigationBar.frame;
tmpFram.origin.y += 20;
self.navigationController.navigationBar.frame = tmpFram;
}
It basically change location of navigation bar.
This is new feature with IOS7. Instead of staring at 20 px navigation bar in IOS7 staring at 0 px. As a solution shift the whole view downwards to 20 px or you can use image for navigation bar with height 64px.
In case it still helps someone, this is what worked for me for moving the Navigation Bar little bit down in ios 7 and above:
-(void)viewWillLayoutSubviews
{
float iosVersion = 7.0;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= iosVersion) {
// iOS 7+
CGRect viewFrame = self.view.frame;
viewFrame.origin.y += 10;
self.view.frame = viewFrame;
}
}
On a device with ios 6.1 and below the Navigation Bar will be unchanged, as it was before.
And this is what I used to make the contents of the Status Bar lighter:
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
If your UIViewController is NOT in a UINavigationController and you're using UIStoryBoard, you can set the "iOS 6/7 Deltas" to 20 for the delta Y, for every subview that needs to be offset from the UIStatusBar.
Using Swift:
As #Scott Berrevoets said in his answer you need to implement the method positionForBar in the protocol UIBarPositioningDelegate, but as the UINavigationBarDelegate protocol implements this protocol :
public protocol UINavigationBarDelegate : UIBarPositioningDelegate {
...
}
You only need to set the delegate of the UINavigationBar you set using Storyboard and implement the method and it's done, like in this way:
class ViewController: UIViewController, UINavigationBarDelegate {
#IBOutlet weak var navigationBar: UINavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return UIBarPosition.TopAttached
}
}
NOTE:
It's worth to mention if you set the position of the y-axis of the navigation bar, let's say to 40 from the top, then it will extend underneath to the top from this position, to simulate the behaviour of the UINavigationController you need to set to 20 from the top.
I hope it will help you.
First, set UIViewControllerBasedStatusBarAppearance to NO in Info.plist.
Then, in AppDelegate's application:didFinishLaunchingWithOptions: method add:
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
[application setStatusBarStyle:UIStatusBarStyleLightContent];
self.window.clipsToBounds = YES;
self.window.frame = CGRectMake(0, 20, self.window.frame.size.width, self.window.frame.size.height-20);
self.window.bounds = CGRectMake(0, 20, self.window.frame.size.width, self.window.frame.size.height);
}
return YES;
In iOS 7 app occupies 100 % of screen size.This not a problem .
http://www.doubleencore.com/2013/09/developers-guide-to-the-ios-7-status-bar/
in earlier iOS window start after statusbar and in iOS 7 window starts from 0px in earlier version view height is 460 (iPhone 4s and earlier) and 548 (iPhone 5) but in iOS 7 view height is 480 (iPhone 4s and earlier) and 568 (iPhone 5 and later) so you have to start view arrangement after 2o px or you have to start view from 20px.
you can write below code in rootviewcontroller or in all viewcontroller for set view from 20px
#define IOS7_HEIGHT 64
- (void)viewDidLayoutSubviews {
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:#"7.0" options:NSNumericSearch] != NSOrderedAscending)
{
CGRect frame=[self.view frame];
if (frame.origin.y!=IOS7_HEIGHT) {
frame.origin.y = IOS7_HEIGHT;
frame.size.height -= IOS7_HEIGHT;
[self.view setFrame:frame];
[self.view layoutSubviews];
}
}
}
here height is 64 because 20 for statusbar and 44 for navigationbar.
try below code it will help you. and your problem will be solved.
For the ones who are having problems implementing #Masterfego 's solution (which is also the official, but I have had problems with Xcode 6.3 and automatic constraints), this is what I did:
I have a UIViewController with an added Navigation Bar. I selected the NAvigation bar and added a height constraint of 64px. We later see a warning that the navbar will be higher (but this is what we do). Finally, you can see that the Status bar looks nice and has the same color as the navbar. :)
PS: I can't post images yet.
You can probably create constraints that are attached to the top layout guide to specify the navigation bar's position relative to the status bar. See the iOS 7 UI Transition Guide: Appearance and Behavior section for more information about using the layout guides.
it's the best answer.
But I wanted know how to use a Storyboard and dragged UINavigationBar on it.
When I implemented the delegate method, and set the return result to UIBarPositionTopAttached, it did not work.
- (void)viewDidLoad{
self.navigationbar.delegate = self;
}
- (UIBarPosition)positionForBar:(id<UIBarPositioning>)bar{
NSLog(#"Got it");
//
// CGRect frame = self.navigaitonBar.frame;
//
// frame = CGRectMake(0, 20, CGRectGetWidth(frame), CGRectGetHeight(frame));
// self.navigaitonBar.frame = frame;
//
// NSLog(#"frame %f",frame.origin.y);
return UIBarPositionTopAttached;
}
If you use Xcode 6 and Swift, you can make it:
Open to info.plist file of your app.
Add a ViewControllerBasedStatusBarAppearance Boolean key if it is not existing and assign value “NO”.
Add “Status bar style” key if it is not existing and select “Opaque black style” value to it.
I was facing issue when full screen ModalViewController was opening from my MainViewController, NavigationBar position was getting changed when user was coming back to MainViewController from ModalViewController.
Issue which I noticed is status bar height was not getting included when user came back to MainViewController. Please debug and check origin of your NavigationBar before and after coming back to your ViewController.
// This method will adjust navigation bar and view content.
private func adjustNavigationControllerIfNeeded() {
var frame = self.view.frame
let navigationBarHeight = self.navigationController!.navigationBar.frame.size.height
if(frame.origin.y == navigationBarHeight && !UIApplication.shared.isStatusBarHidden) {
// If status bar height is not included but it is showing then we have to adjust
our Navigation controller properly
print("Adjusting navigation controller")
let statusBarHeight = UIApplication.shared.statusBarFrame.height
frame.origin.y += statusBarHeight // Start view below navigation bar
frame.size.height -= statusBarHeight
self.view.frame = frame
self.navigationController!.navigationBar.frame.origin.y = statusBarHeight // Move navigation bar
}
}
And call it from viewWillAppear method -
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.adjustNavigationControllerIfNeeded()
}

When hiding the statusbar my navigation bar moves up in iOS7

I am trying to hide the statusbar but maintain the "bigger" navigationbar height. Right now when I hide the statusbar by setting - (BOOL)prefersStatusBarHidden to YES and then calling [self setNeedsStatusBarAppearanceUpdate];. The problem with this is that the navigationbar will slide up and won't leave space for the notification I'm trying to show. Simply adding a view over the statusbar is not an option, our statusbar/navigation has the fancy blur effect. Does anyone have a clue how to maintain the standard navigationbar height with the status bar height and remove the statusbar from that?
Edit; what I ended up doing is taking a risk and getting the UIWindow of the statusbar via a private API and offsetting that.
Edit 2; App got approved with the private API. Be cautious though!
You can create a custom UIView with its frame as
customView.frame=CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height);
Also hide your status bar by following the below steps
Go to info.plist and add two attributes if not present. set "Status bar is initially hidden" to YES and set UIViewControllerBasedStatusBarAppearance to NO. This will hide status bar for your app.
Add this code in your view Controller:
if ([self respondsToSelector:#selector(setEdgesForExtendedLayout:)])
{
self.edgesForExtendedLayout = UIRectEdgeNone;
}
You should use of positionForBar: method of UIBarPositioningDelegate Protocol.
I don't want to put another answer or copy/past so you should take closer look at following question\answers. :)
iOS 7 Status Bar Collides With NavigationBar
iOS 7 UIToolBar Overriding With Status Bar
statusbar overlapping content in iOS7
I had to do this once. I ended up creating a custom navigationBar of my own and then just set the frame as:
navBar.frame=CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height);
It worked for me at the time. Just try it out.
Another workaround here: subclass UINavigationController override method:
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
if (self.navigationBar.frameMinY < 1) {
self.navigationBar.frameHeight = 64;
} else {
self.navigationBar.frameHeight = 44;
}
}
in which set frameMinY is set frame.origin.y and set frameHeight is set frame.size.height

Programmatically get height of navigation bar

I know that the presence of the more view controller (navigation bar) pushes down the UIView by its height. I also know that this height = 44px. I have also discovered that this push down maintains the [self.view].frame.origin.y = 0.
So how do I determine the height of this navigation bar, other than just setting it to a constant?
Or, shorter version, how do I determine that my UIView is showing with the navigation bar on top?
The light bulb started to come on. Unfortunately, I have not discovered a uniform way to correct the problem, as described below.
I believe that my whole problem centers on my autoresizingMasks. And the reason I have concluded that is the same symptoms exist, with or without a UIWebView. And that symptom is that everything is peachy for Portrait. For Landscape, the bottom-most UIButton pops down behind the TabBar.
For example, on one UIView, I have, from top to bottom:
UIView – both springs set (default case) and no struts
UIScrollView - If I set the two springs, and clear everything else (like the UIView), then the UIButton intrudes on the object immediately above it. If I clear everything, then UIButton is OK, but the stuff at the very top hides behind the StatusBar Setting only the top strut, the UIButton pops down behind the Tab Bar.
UILabel and UIImage next vertically – top strut set, flexible everywhere else
Just to complete the picture for the few that have a UIWebView:
UIWebView - Struts: top, left, right Springs: both
UIButton – nothing set, i.e., flexible everywhere
Although my light bulb is dim, there appears to be hope.
Please bear with me because I needed more room than that provided for a short reply comment.
Thanks for trying to understand what I am really fishing for ... so here goes.
1) Each UIViewController (a TabBar app) has a UIImage, some text and whatever on top. Another common denominator is a UIButton on the bottom. On some of the UIViewControllers I have a UIWebView above the UIButton.
So, UIImage, text etc. UIWebView (on SOME) UIButton
Surrounding all the above is a UIScrollView.
2) For those that have a UIWebView, its autoresizingMask looks like:
—
|
—
^
|
|
|—| ←----→ |—|
|
|
V
The UIButton's mask has nothing set, i.e., flexible everywhere
Within my -viewDidLoad, I call my -repositionSubViews within which I do the following:
If there is no UIWebView, I do nothing except center the UIButton that I placed with IB.
If I do have a UIWebView, then I determine its *content*Height and set its frame to enclose the entire content.
UIScrollView *scrollViewInsideWebView = [[webView_ subviews] lastObject];
webViewContentHeight = scrollViewInsideWebView.contentSize.height;
[webView_ setFrame:CGRectMake(webViewOriginX, webViewOriginY,
sameWholeViewScrollerWidth, webViewContentHeight)]
Once I do that, then I programmatically push the UIButton down so that it ends up placed below the UIWebView.
Everything works, until I rotate it from Portrait to Landscape.
I call my -repositionSubViews within my -didRotateFromInterfaceOrientation.
Why does the content height of my UIWebView not change with rotation?.
From Portrait to Landscape, the content width should expand and the content height should shrink. It does visually as it should, but not according to my NSLog.
Anyway, with or without a UIWebView, the button I've talked about moves below the TabBar when in Landscape mode but it will not scroll up to be seen. I see it behind the TabBar when I scroll "vigorously", but then it "falls back" behind the TabBar.
Bottom line, this last is the reason I've asked about the height of the TabBar and the NavigationBar because the TabBar plants itself at the bottom of the UIView and the NavigationBar pushes the UIView down.
Now, I'm going to add a comment or two here because they wouldn't have made sense earlier.
With no UIWebView, I leave everything as is as seen by IB.
With a UIWebView, I increase the UIWebView's frame.height to its contentHeight and also adjust upward the height of the surrounding UIScrollView that surrounds all the sub-views.
Well there you have it.
Do something like this ?
NSLog(#"Navframe Height=%f",
self.navigationController.navigationBar.frame.size.height);
The swift version is located here
UPDATE
iOS 13
As the statusBarFrame was deprecated in iOS13 you can use this:
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
With iPhone-X, height of top bar (navigation bar + status bar) is changed (increased).
Try this if you want exact height of top bar (both navigation bar + status bar):
UPDATE
iOS 13
As the statusBarFrame was deprecated in iOS13 you can use this:
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
Objective-C
CGFloat topbarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height +
(self.navigationController.navigationBar.frame.size.height ?: 0.0));
Swift 4
let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
For ease, try this UIViewController extension
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
Swift 3
let topBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
Swift version:
let navigationBarHeight: CGFloat = self.navigationController!.navigationBar.frame.height
iOS 14
For me, view.window is null on iOS 14.
extension UIViewController {
var topBarHeight: CGFloat {
var top = self.navigationController?.navigationBar.frame.height ?? 0.0
if #available(iOS 13.0, *) {
top += UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
} else {
top += UIApplication.shared.statusBarFrame.height
}
return top
}
}
Swift 5
If you want to get the navigation bar height, use the maxY property that considers the safeArea size as well, like this:
let height = navigationController?.navigationBar.frame.maxY
Support iOS 13 and Below:
extension UIViewController {
var topbarHeight: CGFloat {
if #available(iOS 13.0, *) {
return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
} else {
let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
return topBarHeight
}
}
}
Did you try this?
let barHeight = self.navigationController?.navigationBar.frame.height ?? 0
UIImage*image = [UIImage imageNamed:#"logo"];
float targetHeight = self.navigationController.navigationBar.frame.size.height;
float logoRatio = image.size.width / image.size.height;
float targetWidth = targetHeight * logoRatio;
UIImageView*logoView = [[UIImageView alloc] initWithImage:image];
// X or Y position can not be manipulated because autolayout handles positions.
//[logoView setFrame:CGRectMake((self.navigationController.navigationBar.frame.size.width - targetWidth) / 2 , (self.navigationController.navigationBar.frame.size.height - targetHeight) / 2 , targetWidth, targetHeight)];
[logoView setFrame:CGRectMake(0, 0, targetWidth, targetHeight)];
self.navigationItem.titleView = logoView;
// How much you pull out the strings and struts, with autolayout, your image will fill the width on navigation bar. So setting only height and content mode is enough/
[logoView setContentMode:UIViewContentModeScaleAspectFit];
/* Autolayout constraints also can not be manipulated since navigation bar has immutable constraints
self.navigationItem.titleView.translatesAutoresizingMaskIntoConstraints = false;
NSDictionary*metricsArray = #{#"width":[NSNumber numberWithFloat:targetWidth],#"height":[NSNumber numberWithFloat:targetHeight],#"margin":[NSNumber numberWithFloat:20]};
NSDictionary*viewsArray = #{#"titleView":self.navigationItem.titleView};
[self.navigationItem.titleView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"|-(>margin=)-H:[titleView(width)]-(>margin=)-|" options:NSLayoutFormatAlignAllCenterX metrics:metricsArray views:viewsArray]];
[self.navigationItem.titleView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:[titleView(height)]" options:0 metrics:metricsArray views:viewsArray]];
NSLog(#"%f", self.navigationItem.titleView.width );
*/
So all we actually need is
UIImage*image = [UIImage imageNamed:#"logo"];
UIImageView*logoView = [[UIImageView alloc] initWithImage:image];
float targetHeight = self.navigationController.navigationBar.frame.size.height;
[logoView setFrame:CGRectMake(0, 0, 0, targetHeight)];
[logoView setContentMode:UIViewContentModeScaleAspectFit];
self.navigationItem.titleView = logoView;
Handy Swift 4 extension, in case it's helpful to someone else. Works even if the current view controller does not display a navigation bar.
import UIKit
extension UINavigationController {
static public func navBarHeight() -> CGFloat {
let nVc = UINavigationController(rootViewController: UIViewController(nibName: nil, bundle: nil))
let navBarHeight = nVc.navigationBar.frame.size.height
return navBarHeight
}
}
Usage:
UINavigationController.navBarHeight()
The light bulb started to come on. Unfortunately, I have not discovered a uniform way to correct the problem, as described below.
I believe that my whole problem centers on my autoresizingMasks. And the reason I have concluded that is the same symptoms exist, with or without a UIWebView. And that symptom is that everything is peachy for Portrait. For Landscape, the bottom-most UIButton pops down behind the TabBar.
For example, on one UIView, I have, from top to bottom:
UIView – both springs set (default case) and no struts
UIScrollView -
If I set the two springs, and clear everything else (like the UIView), then the UIButton intrudes on the object immediately above it.
If I clear everything, then UIButton is OK, but the stuff at the very top hides behind the StatusBar
Setting only the top strut, the UIButton pops down behind the Tab Bar.
UILabel and UIImage next vertically – top strut set, flexible everywhere else
Just to complete the picture for the few that have a UIWebView:
UIWebView -
Struts: top, left, right
Springs: both
UIButton – nothing set, i.e., flexible everywhere
Although my light bulb is dim, there appears to be hope.
My application has a couple views that required a customized navigation bar in the UI for look & feel, however without navigation controller. And the application is required to support iOS version prior to iOS 11, so the handy safe area layout guide could not be used, and I have to adjust the position and height of navigation bar programmatically.
I attached the Navigation Bar to its superview directly, skipping the safe area layout guide as mentioned above. And the status bar height could be retrieved from UIApplication easily, but the default navigation bar height is really a pain-ass...
It struck me for almost half a night, with a number of searching and testing, until I finally got the hint from another post (not working to me though), that you could actually get the height from UIView.sizeThatFits(), like this:
- (void)viewWillLayoutSubviews {
self.topBarHeightConstraint.constant = [UIApplication sharedApplication].statusBarFrame.size.height;
self.navBarHeightConstraint.constant = [self.navigationBar sizeThatFits:CGSizeZero].height;
[super viewWillLayoutSubviews];
}
Finally, a perfect navigation bar looking exactly the same as the built-in one!
Here is the beginning of my response to your update:
Why does the content height of my UIWebView not change with rotation?.
Could it be that because your auto resize doesn't have the autoresizingMask for all directions?
Another suggestion before I come back for this, could you use a toolbar for your needs. It's a little simpler, will always be on the bottom, auto-rotates/positions. You can hide/show it at will etc. Kind of like this: http://cdn.artoftheiphone.com/wp-content/uploads/2009/01/yellow-pages-iphone-app-2.jpg
You may have looked at that option, but just throwing it out there.
Another idea, could you possibly detect what orientation you are rotating from, and just place the button programmatically to adjust for the tab bar. (This is possible with code)
I have used:
let originY: CGFloat = self.navigationController!.navigationBar.frame.maxY
Working great if you want to get the navigation bar height AND its Y origin.
If you want to get the navigationBar height only, it's simple:
extension UIViewController{
var navigationBarHeight: CGFloat {
return self.navigationController?.navigationBar.frame.height ?? 0.0
}
}
However, if you need the height of top notch of iPhone you don't need to get the navigationBar height and add to it the statusBar height, you can simply call safeAreaInsets that's why exist.
self.view.safeAreaInsets.top
Swift : programmatically adding a web view right under the navigation bar
From iOS11 the key to position the view below the navigation bar is to use safeAreaLayoutGuide
From the Apple docs (link):
The layout guide representing the portion of your view that is unobscured by bars and other content.
So in code I will put the top constraint using view.safeAreaLayoutGuide.topAnchor
Again the whole thing will be for example:
import WebKit
class SettingsViewController: UIViewController {
let webView = WKWebView()
let url = URL(string: "https://www.apple.com")
override func viewDidLoad() {
super.viewDidLoad()
configureWebView()
}
override func viewWillAppear(_ animated: Bool) {
follow(url: url)
}
func follow(url: URL?) {
if let url = url {
let request = URLRequest(url: url)
webView.load(request)
}
}
func configureWebView() {
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}

Resources