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.
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)
In Swift 3 You will get the navigation bar height by using the following way:
self.navigationController?.navigationBar.intrinsicContentSize.height
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With