So I have a view with a text field in it, but the text field is at the bottom. When I click the keyboard, it pops up and covers the text field, this is my problem. I was wondering if it is at all possible to push the rest of the view up when a keyboard comes up?
Asked
Active
Viewed 7,711 times
3 Answers
7
You can register your view controller to be notified when the keyboard is about to be shown, then you push your view up.
class ViewController: UIViewController {
var keyboardAdjusted = false
var lastKeyboardOffset: CGFloat = 0.0
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if keyboardAdjusted == false {
lastKeyboardOffset = getKeyboardHeight(notification)
view.frame.origin.y -= lastKeyboardOffset
keyboardAdjusted = true
}
}
func keyboardWillHide(notification: NSNotification) {
if keyboardAdjusted == true {
view.frame.origin.y += lastKeyboardOffset
keyboardAdjusted = false
}
}
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
}

Ahmed Onawale
- 3,992
- 1
- 17
- 21
0
You can check this tutorial Move UITextField so keyboard does not hide it
You will find demo for this here
Or you can check the answer of this stackoverflow Move textfield when keyboard appears swift
Best answer there is to manage by updating bottom constraint like this
func keyboardWasShown(notification: NSNotification) {
var info = notification.userInfo!
var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.bottomConstraint.constant = keyboardFrame.size.height + 20
})
}

Community
- 1
- 1

Omar Faruqe
- 135
- 2
- 7
-1
You should put text field into UIScrollView
and adjust its contentInset
on UIKeyboardDidShowNotification
.
Read this help page: https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW7

Evgeny Sureev
- 1,008
- 10
- 16