Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a navigation bar hight in iOS programatically

I have to move up my view when keyboardwillshown then it back to it's normal place when keyboard will hide

Actually I have used this code on viewdidload method:

override func viewDidLoad() { 

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) 

}

Here is the method which I used for move up and down

func keyboardWillShow(notification:NSNotification){ 

    print("keyboardwillshow")
    let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()

    self.view.frame = CGRectMake(0.0, -keyboardSize!.size.height + (self.navigationController?.navigationBar.frame.size.height)! + 20 , self.view.frame.size.width, self.view.frame.size.height )  

}

func keyboardWillHide(notification:NSNotification){

    self.view.frame = CGRectMake(0.0,(self.navigationController?.navigationBar.frame.size.height)!, self.view.frame.size.width, self.view.frame.size.height)
//  self.view.frame.origin.y += 350

}

While I run this program, it will show a run time error that is

unexpected found a nil while unwrapping

Please help me fix this.

like image 806
sritharan Avatar asked Feb 25 '16 10:02

sritharan


2 Answers

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):

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)
like image 134
Krunal Avatar answered Nov 14 '22 22:11

Krunal


In Swift 3 You will get the navigation bar height by using the following way:

self.navigationController?.navigationBar.intrinsicContentSize.height
like image 44
Ram Madhavan Avatar answered Nov 14 '22 22:11

Ram Madhavan