Move view with keyboard using Swift

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Move view with keyboard using Swift



I have an app that has a text field on the lower half of the view.
This means that when I go to type in the text field the keyboard covers the textfield.



How would I go about moving the view upwards while typing so I can see what i'm typing and then moving it back down to its original place when the keyboard disappears?



I've looked everywhere but all the solutions appear to be in Obj-C which I can't quite convert just yet.



Any help would be greatly appreciated.





The best way to do this is to place your content inside a UIScrollView, then adjust the scroll view's contentInset property by the height of the keyboard when it's shown. Absolutely do not assume the keyboard height--use the value from the "keyboard will show" notification.
– nielsbot
Oct 2 '15 at 16:47





In fact, the Apple docs tell you how to do this, under "Managing the Keyboard": developer.apple.com/library/ios/documentation/StringsTextFonts/…
– nielsbot
Oct 2 '15 at 16:48






I think all answers below does not take into consideration one case: what if you have multiple textfields and some of them are located at the top of the screen? Anytime user taps that textfield, it goes up beyond the screen, I'm pretty sure the correct answer should detect whether it is actually needed to scroll view up when keyboard appears
– DCDC
Aug 18 '16 at 22:06


it is actually needed to scroll view up when keyboard appears





This answer is able to detect whether it is actually needed to scroll the view up when the keyboard appears by checking if the textfield currently being edited occupies the same space as the keyboard: stackoverflow.com/a/28813720/6749410
– HirdayGupta
May 29 at 8:51




33 Answers
33



Here is a solution, without handling the switch from one textField to another:


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


func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
self.view.frame.origin.y -= keyboardSize.height



func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
self.view.frame.origin.y += keyboardSize.height




To solve this, replace the two functions keyboardWillShow/Hide with these:


keyboardWillShow/Hide


func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
if view.frame.origin.y == 0
self.view.frame.origin.y -= keyboardSize.height




func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
if view.frame.origin.y != 0
self.view.frame.origin.y += keyboardSize.height




override func viewDidLoad()
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)


@objc func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y == 0
self.view.frame.origin.y -= keyboardSize.height




@objc func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y != 0
self.view.frame.origin.y += keyboardSize.height





EDIT FOR SWIFT 4.0:


override func viewDidLoad()
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)


@objc func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y == 0
self.view.frame.origin.y -= keyboardSize.height




@objc func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y != 0
self.view.frame.origin.y += keyboardSize.height







This is the only code that's works. This might be the "best answer". I do not understand why so few thumbs up. Thank you Boris, thank you very much.
– RikiRiocma
Jul 24 '15 at 8:22






If the user touches another text field while the keyboard is present the view will be pushed further up which causes a black area (the size of the keyboard) - we need to fix that by having a variable that tracks if the keyboard is present or not. e.g if keyboardPresent == true then dont move the view origin etc etc
– jonprasetyo
Dec 16 '15 at 15:09





@Matthew Lin use a boolean so the functions keyboardWillShow and hide only works one time
– iluvatar_GR
Mar 8 '16 at 14:42





Just one suggestion, so that you don't have to debug a lot like I did. If you have multiple uitextfields on the same screen, keyboard-size may vary (it doesn't show suggestions for some inputs based on your settings), so it is advisable to set self.view.frame.origin.y = 0 , everytime you dismiss the keyboard. For example, it would show sugeestions for your email textfield, so keyboard size would increase, and it won't show suggestions for password field, so keyboard size would decrease.
– Vandan Patel
Dec 21 '16 at 20:55






You need to use UIKeyboardFrameEndUserInfoKey rather than UIKeyboardFrameBeginUserInfoKey when obtaining the keyboard size. I am not sure why at the moment, but the former will yield more consistent results.
– jshapy8
Nov 27 '17 at 5:46


UIKeyboardFrameEndUserInfoKey


UIKeyboardFrameBeginUserInfoKey



One of the popular answers on this thread uses the following code:


func keyboardWillShow(sender: NSNotification)
self.view.frame.origin.y -= 150

func keyboardWillHide(sender: NSNotification)
self.view.frame.origin.y += 150



There's an obvious problem with offsetting your view by a static amount. It'll look nice on one device but will look bad on any other size configuration. You'll need to get the keyboards height and use that as your offset value.



Here's a solution that works on all devices and handles the edge-case where the user hides the predictive text field while typing.



Important to note below, we're passing self.view.window in as our object parameter. This will provide us with data from our Keyboard, such as its height!


@IBOutlet weak var messageField: UITextField!

override func viewDidLoad()
super.viewDidLoad()

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


func keyboardWillHide(sender: NSNotification)
let userInfo: [NSObject : AnyObject] = sender.userInfo!
let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
self.view.frame.origin.y += keyboardSize.height



We'll make it look nice on all devices and handle the case where the user adds or removes the predictive text field.


func keyboardWillShow(sender: NSNotification)
let userInfo: [NSObject : AnyObject] = sender.userInfo!
let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
let offset: CGSize = userInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue.size

if keyboardSize.height == offset.height
UIView.animateWithDuration(0.1, animations: () -> Void in
self.view.frame.origin.y -= keyboardSize.height
)
else
UIView.animateWithDuration(0.1, animations: () -> Void in
self.view.frame.origin.y += keyboardSize.height - offset.height
)




Don't forget to remove your observers before you leave the view to prevent unnecessary messages from being transmitted.


override func viewWillDisappear(animated: Bool)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: self.view.window)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: self.view.window)



Update based on question from comments:



If you have two or more text-fields, you can check to see if your view.frame.origin.y is at zero.


func keyboardWillShow(sender: NSNotification)
let userInfo: [NSObject : AnyObject] = sender.userInfo!

let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
let offset: CGSize = userInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue.size

if keyboardSize.height == offset.height
if self.view.frame.origin.y == 0
UIView.animateWithDuration(0.1, animations: () -> Void in
self.view.frame.origin.y -= keyboardSize.height
)

else
UIView.animateWithDuration(0.1, animations: () -> Void in
self.view.frame.origin.y += keyboardSize.height - offset.height
)

print(self.view.frame.origin.y)





when dealing with multiple text fields, the view keeps moving up and does not come back down
– Mugunthan Balakrishnan
Oct 13 '15 at 9:07





You're going to have to change your conditions to account for the text fields
– Dan Beaulieu
Oct 13 '15 at 11:05





Would you be able to help out with some sample code 😊
– Mugunthan Balakrishnan
Oct 13 '15 at 11:06





thanks for the response, i found the answer i was looking for at this thread on stack overflow stackoverflow.com/questions/1126726/…
– Mugunthan Balakrishnan
Oct 14 '15 at 5:43





@MugunthanBalakrishnan thanks for bringing this up, I've added a solution.
– Dan Beaulieu
Oct 17 '15 at 22:14



Easiest way that doesn't even require any code:



The object will auto-move up with the keyboard, in sync.





To select the bottom constraint you can also go to Size Inspector, then double-click on the constraint in the list - raywenderlich.com/wp-content/uploads/2015/09/…
– gammachill
May 7 '16 at 9:46






This worked perfect for me. it's literally a 2 step process. 1. Add the KeyboardLayoutConstraint.swift, 2. In storyboard, create a bottom constrain for the view or text field. NOTE: I deleted my constraints and added just 1 constraint to bottom of the view or textfield and change its class from NSLayoutConstraint to KeyboardLayoutConstraint. Then any views/textfields etc. above I just connected constraints from that item to the item with a single KeyboardLayoutConstraint and the result was all items in view moved UP/DOWN when Key Board Appears/Disappears
– Brian
Dec 29 '16 at 18:58






This is the best solution, the provided code does not hardcode any values such as the length or curve of the animation, or the size of the keyboard. It is also easy to understand.
– miguelSantirso
Sep 25 '17 at 14:17





This is working for me, but I get an extra 50px of space between the top of the keyboard and the bottom of my scrollView. I'm wondering if it's due to the Safe Area bottom constraint I'm using. Anyone run into this?
– Clifton Labrum
Jul 9 at 20:00





Perfect, it works like a charm with swift 4.
– Dohab
Aug 3 at 12:41




Add this to your viewcontroller. Works like a charm. Just adjust the values.


override func viewDidLoad()
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);


@objc func keyboardWillShow(sender: NSNotification)
self.view.frame.origin.y -= 150

@objc func keyboardWillHide(sender: NSNotification)
self.view.frame.origin.y += 150





This works for me. However it is a little jerky. How can I get this to move up smoothley? also is there a way to only apply it to one of the textfields as it currently does this for all. :(
– DannieCoderBoi
Feb 6 '15 at 1:56





It might not work with "Auto-Layout" so consider deactivating it if so.
– Teodor Ciuraru
Mar 3 '15 at 22:40





It causes some funky behavior with autolayout @Josh, you are mistaken
– Mike
Jun 6 '15 at 20:22





Don't do this! You cannot assume the keyboard is a certain size.
– nielsbot
Oct 2 '15 at 16:39





Should use keyboardSize. What happens when you have accessory views and different keyboard heights on devices? Detached keyboard?
– xtrinch
Jul 1 '16 at 22:53



I improved one of the answers a bit to make it work with different keyboards & different textviews/fields on one page:



Add observers:


override func viewWillAppear(_ animated: Bool)
super.viewWillAppear(animated)

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)),
name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
name: NSNotification.Name.UIKeyboardWillHide, object: nil)


func keyboardWillHide()
self.view.frame.origin.y = 0


func keyboardWillChange(notification: NSNotification)

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
if YOURTEXTVIEW.isFirstResponder
self.view.frame.origin.y = -keyboardSize.height





Remove observers:


override func viewWillDisappear(_ animated: Bool)
super.viewWillDisappear(animated)

NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.UIKeyboardWillHide, object: nil)





thanks, this was the best solution for me on iOS11
– gypsyDev
Sep 29 '17 at 1:04





this solution works better than accepted answer. Accepted answer shows the keyboard only once which to me is a bug :)
– Masih
Nov 3 '17 at 17:28



I see all answers are moving the view itself by the value of the keyboard height. Well, I have an elaborate answer, which could be useful if you are using constraints i.e autolayout, that moves a view by changing its constraint value (bottom or top constraints for example) by a predefined value or you can use keyboard size value.


autolayout



In this example, I use bottom constraint from the textfield to Bottom Layout View with initial value of 175.


@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

override func viewDidLoad()
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);


func keyboardWillShow(notification: NSNotification)
//To retrieve keyboard size, uncomment following line
//let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
bottomConstraint.constant = 260
UIView.animateWithDuration(0.3)
self.view.layoutIfNeeded()



func keyboardWillHide(notification: NSNotification)
//To retrieve keyboard size, uncomment following line
//let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
bottomConstraint.constant = 175
UIView.animateWithDuration(0.3)
self.view.layoutIfNeeded()




I noticed that the other answers involved cutting some of the top from the view. If you want to simply resize the view without cutting any content, just try this method :)


func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
self.view.setTranslatesAutoresizingMaskIntoConstraints(true)
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.height - keyboardSize.height)



func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
self.collectionView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.height + keyboardSize.height)




For Swift 3, I made a UIViewController subclass since I needed constant behavior in all View Controllers.


class SomeClassVC: UIViewController

//MARK: - Lifecycle
override func viewDidLoad()
super.viewDidLoad()

addKeyboardObservers()


override func viewWillDisappear(_ animated: Bool)
super.viewWillDisappear(animated)

removeKeyboardObservers()


//MARK: - Overrides
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
view.endEditing(true)


//MARK: - Help
func addKeyboardObservers()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)


func removeKeyboardObservers()
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)


func keyboardWillShow(notification: NSNotification)
let keyboardHeight = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height
UIView.animate(withDuration: 0.1, animations: () -> Void in
self.view.window?.frame.origin.y = -1 * keyboardHeight!
self.view.layoutIfNeeded()
)


func keyboardWillHide(notification: NSNotification)
UIView.animate(withDuration: 0.1, animations: () -> Void in
self.view.window?.frame.origin.y = 0
self.view.layoutIfNeeded()
)


func resignTextFieldFirstResponders()
for textField in self.view.subviews where textField is UITextField
textField.resignFirstResponder()



func resignAllFirstResponders()
view.endEditing(true)






Thanks a lot for this. The cleanest solution that worked for me. Everything else that I surveyed just doesn't cut it like this one.
– Noor Dawod
Aug 9 '17 at 7:53





Inspired by Pavle's solution, I upgraded it to automatically raise the keyboard by a certain percentage of the remaining available space and also find the focused field recursively for proper layout. Grab it here: gist.github.com/noordawod/24d32b2ce8363627ea73d7e5991009a0
– Noor Dawod
Aug 9 '17 at 8:45





Glad it was useful :)
– Pavle Mijatovic
Aug 29 '17 at 9:07





Perfect! Much better and Elegant than the Current response. Moderators, please take note ;-)
– Hernan Arber
Sep 6 '17 at 9:26





My tab bar is also moving up with window! :(
– Alfi
Dec 21 '17 at 15:29




For Black Screen Error ( Swift 4 ) .



I fixed the black screen problem. In the verified solution The keyboard height changes after tapping and this is causing black screen.



Have to use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey


var isKeyboardAppear = false

override func viewDidLoad()
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)


@objc func keyboardWillShow(notification: NSNotification)
if !isKeyboardAppear
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y == 0
self.view.frame.origin.y -= keyboardSize.height


isKeyboardAppear = true



@objc func keyboardWillHide(notification: NSNotification)
if isKeyboardAppear
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y != 0
self.view.frame.origin.y += keyboardSize.height


isKeyboardAppear = false






Thanks for this solution. That works fine for me, just as expected.
– MK87
Jul 26 at 14:55





Won't work if there is a tabbar. You have to calculate tabbar height, otherwise there will be a black screen gap between keyboard and view.
– Ankur Lahiry
Sep 3 at 6:09



For Swift 3


func textFieldDidBeginEditing(_ textField: UITextField) // became first responder

//move textfields up
let myScreenRect: CGRect = UIScreen.main.bounds
let keyboardHeight : CGFloat = 216

UIView.beginAnimations( "animateView", context: nil)
var movementDuration:TimeInterval = 0.35
var needToMove: CGFloat = 0

var frame : CGRect = self.view.frame
if (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight - 30))
needToMove = (textField.frame.origin.y + textField.frame.size.height + UIApplication.shared.statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight - 30);


frame.origin.y = -needToMove
self.view.frame = frame
UIView.commitAnimations()


func textFieldDidEndEditing(_ textField: UITextField)
//move textfields back down
UIView.beginAnimations( "animateView", context: nil)
var movementDuration:TimeInterval = 0.35
var frame : CGRect = self.view.frame
frame.origin.y = 0
self.view.frame = frame
UIView.commitAnimations()



My two cents for beginners:
in above samples someone changes coordinates, other uses "autoresizing mask", and other constraints:



As Apple says, do not mix these 3 types of logic.
If You have constraints in Storyboard, do not try to change x/y. It definitively not work.



The validated answer doesn't take in account the textfield position and has some bug (double displacement, never come back the primary position, displacement even if the texfield is on top of the view...)



The idea is :



then we will be able to move the view only if necessary and of the specific displacement in oder to have the focused texField just over the keyboard



Here is the code :



Swift 4


class ViewController: UIViewController, UITextFieldDelegate

var textFieldRealYPosition: CGFloat = 0.0

override func viewDidLoad()
super.viewDidLoad()

NotificationCenter.default.addObserver(self, selector: #selector(VehiculeViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(VehiculeViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

// Delegate all textfields




@objc func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
let distanceBetweenTextfielAndKeyboard = self.view.frame.height - textFieldRealYPosition - keyboardSize.height
if distanceBetweenTextfielAndKeyboard < 0
UIView.animate(withDuration: 0.4)
self.view.transform = CGAffineTransform(translationX: 0.0, y: distanceBetweenTextfielAndKeyboard)






@objc func keyboardWillHide(notification: NSNotification)
UIView.animate(withDuration: 0.4)
self.view.transform = .identity




func textFieldDidBeginEditing(_ textField: UITextField)
textFieldRealYPosition = textField.frame.origin.y + textField.frame.height
//take in account all superviews from textfield and potential contentOffset if you are using tableview to calculate the real position





Here is my solution (actually this code is for the case when you have few textfields in your view, this works also for the case when you have one textfield)


class MyViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: UITextField!

var activeTextField: UITextField!
var viewWasMoved: Bool = false


override func viewDidLoad()
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PrintViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PrintViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)


override func viewDidDisappear(animated: Bool)
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)


func textFieldDidBeginEditing(textField: UITextField)
self.activeTextField = textField


func textFieldDidEndEditing(textField: UITextField)
self.activeTextField = nil


func textFieldShouldReturn(textField: UITextField) -> Bool
textField.resignFirstResponder()
return true



func keyboardWillShow(notification: NSNotification)

let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()

var aRect: CGRect = self.view.frame
aRect.size.height -= keyboardSize!.height

let activeTextFieldRect: CGRect? = activeTextField?.frame
let activeTextFieldOrigin: CGPoint? = activeTextFieldRect?.origin

if (!CGRectContainsPoint(aRect, activeTextFieldOrigin!))
self.viewWasMoved = true
self.view.frame.origin.y -= keyboardSize!.height
else
self.viewWasMoved = false



func keyboardWillHide(notification: NSNotification)
if (self.viewWasMoved)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
self.view.frame.origin.y += keyboardSize.height







Don't forget to set the Delegate to the textFields
– SwingerDinger
Apr 14 '16 at 8:33





Change the condition in keyboardwillshow as, if (!CGRectContainsPoint(aRect, newOrgin!) && !self.viewWasMoved)
– KingofBliss
Jul 4 '16 at 6:37





and remove that else condition in keyboardwillshow
– KingofBliss
Jul 4 '16 at 6:38





add self.viewWasMoved = false when u resetting the frame
– KingofBliss
Jul 4 '16 at 6:40



Updated for Swift 3...



As others have said, you need to add notification observers in your controller's viewDidLoad() method, like so:


NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil)
notification in
self.keyboardWillShow(notification)


NotificationCenter.default.addObserver(forName: .UIKeyboardWillHide, object: nil, queue: nil)
notification in
self.keyboardWillHide(notification)


NotificationCenter.default.addObserver(forName: .UIKeyboardDidShow, object: nil, queue: nil)
_ in
self.enableUserInteraction()


NotificationCenter.default.addObserver(forName: .UIKeyboardDidHide, object: nil, queue: nil)
_ in
self.enableUserInteraction()



Remember to remove your observers where appropriate (I do it in the viewWillDisappear() method)


NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardDidHide, object: nil)



Then, implement your show and hide methods - notice the line that tells the app to ignore interaction events (beginIgnoringInteractionEvents). This is important since without it, the user could tap on a field or even a scrollview and cause the shift to occur a second time, resulting in a terrible UI glitch. Ignoring interaction events prior to the keyboard showing and hiding will prevent this:


func keyboardWillShow(notification: Notification)

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue

UIApplication.shared.beginIgnoringInteractionEvents()
self.view.frame.origin.y -= keyboardSize.height
// add this line if you are shifting a scrollView, as in a chat application
self.timelineCollectionView.contentInset.top += keyboardSize.height



func keyboardWillHide(notification: Notification)

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue

UIApplication.shared.beginIgnoringInteractionEvents()
self.view.frame.origin.y += keyboardSize.height
// add this line if you are shifting a scrollView, as in a chat application
self.timelineCollectionView.contentInset.top -= keyboardSize.height




Lastly, re-enable user interactions (remember, this method fires after the keyboard didShow or didHide):


func enableUserInteraction()

UIApplication.shared.endIgnoringInteractionEvents()



If you have 2 or more text fields on the same VC, and the user taps on one of them and then taps on the other one, without calling the function keyboardWillHide, the view is going upwards one more time, which is not necessary, because you'll have the keyboard, a blank space which has the height of the keyboard, and then the view, using the code in the answer I edited:


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


func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
self.view.frame.origin.y -= keyboardSize.height



func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
self.view.frame.origin.y += keyboardSize.height




To solve this, replace the two functions "KeyboardWillShow/Hide" to these:


func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
if view.frame.origin.y == 0
self.view.frame.origin.y -= keyboardSize.height




func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
if view.frame.origin.y != 0
self.view.frame.origin.y += keyboardSize.height







sorry for the lack of organised space
– Mr. Xcoder
Jun 30 '16 at 15:52




Swift 4:



I was having an issue with the most accepted answer, in which hiding the keyboard did not return the view all the way to the bottom of the page (only partially). This worked for me (+updated for Swift 4).


override func viewDidLoad()
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)


@objc func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y == 0
self.view.frame.origin.y -= keyboardSize.height




@objc func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y != 0
self.view.frame.origin.y = 0





this video tutorial is the best. 7 mins long and it'll just make so much sense. Such a simple solution for when you have multiple text fields and want the scroll view to move "x" amount of pixels when that specific textfield is tapped.



https://youtu.be/VuiPGJOEBH4



Just these steps:



-Place all your textfields within a scrollview that is constrained to the edges of the view.



-Connect all the textfields and scroll view as delegates to the view controller.



-Connect all textfields and scroll view with an IBOutlet.


class ViewController: UIViewController, UITextFieldDelegate {



-Add UITextFieldDelegate protocol to your class


@IBOutlet var stateAddress: UITextField!
@IBOutlet var zipAddress: UITextField!
@IBOutlet var phoneNumber: UITextField!
@IBOutlet var vetEmailAddress: UITextField!
@IBOutlet weak var scrollView: UIScrollView!



-Add UITextFieldDelegate methods to your swift file:


func textFieldShouldReturn(textField: UITextField) -> Bool

textField.resignFirstResponder()
return true



func textFieldDidBeginEditing(textField: UITextField)

if (textField == self.stateAddress)
scrollView.setContentOffset(CGPointMake(0, 25), animated: true)

else if (textField == self.zipAddress)
scrollView.setContentOffset(CGPointMake(0, 57), animated: true)

else if (textField == self.phoneNumber)
scrollView.setContentOffset(CGPointMake(0, 112), animated: true)

else if (textField == self.vetEmailAddress)
scrollView.setContentOffset(CGPointMake(0, 142), animated: true)



func textFieldDidEndEditing(textField: UITextField)

scrollView.setContentOffset(CGPointMake(0, 0), animated: true)



The first method just activates the return button on the keyboard to dismiss the keyboard. The second is when you tap into whatever specific textfield then setting the y offset of how far your scrollview scrolls (mine is based off of the y location on my view controllers 25,57,112,142). The last says when you tap away from the keyboard the scrollview goes back to original location.



I made my view pixel perfect this way!



This feature shud have come built in Ios, however we need to do externally.

Insert the below code

* To move view when textField is under keyboard,

* Not to move view when textField is above keyboard

* To move View based on the height of the keyboard when needed.

This works and tested in all cases.


import UIKit

class NamVcc: UIViewController, UITextFieldDelegate

@IBOutlet weak var NamTxtBoxVid: UITextField!

var VydTxtBoxVar: UITextField!
var ChkKeyPadDspVar: Bool = false
var KeyPadHytVal: CGFloat!

override func viewDidLoad()

super.viewDidLoad()

NamTxtBoxVid.delegate = self


override func viewWillAppear(animated: Bool)

NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(TdoWenKeyPadVyd(_:)),
name:UIKeyboardWillShowNotification,
object: nil);
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(TdoWenKeyPadHyd(_:)),
name:UIKeyboardWillHideNotification,
object: nil);


func textFieldDidBeginEditing(TxtBoxPsgVar: UITextField)

self.VydTxtBoxVar = TxtBoxPsgVar


func textFieldDidEndEditing(TxtBoxPsgVar: UITextField)

self.VydTxtBoxVar = nil


func textFieldShouldReturn(TxtBoxPsgVar: UITextField) -> Bool

self.VydTxtBoxVar.resignFirstResponder()
return true


override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)

view.endEditing(true)
super.touchesBegan(touches, withEvent: event)


func TdoWenKeyPadVyd(NfnPsgVar: NSNotification)

if(!self.ChkKeyPadDspVar)

self.KeyPadHytVal = (NfnPsgVar.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().height

var NonKeyPadAraVar: CGRect = self.view.frame
NonKeyPadAraVar.size.height -= self.KeyPadHytVal

let VydTxtBoxCenVal: CGPoint? = VydTxtBoxVar?.frame.origin

if (!CGRectContainsPoint(NonKeyPadAraVar, VydTxtBoxCenVal!))

self.ChkKeyPadDspVar = true
UIView.animateWithDuration(1.0,
animations:
self.view.frame.origin.y -= (self.KeyPadHytVal),
completion: nil)

else

self.ChkKeyPadDspVar = false





func TdoWenKeyPadHyd(NfnPsgVar: NSNotification)

if (self.ChkKeyPadDspVar)

self.ChkKeyPadDspVar = false
UIView.animateWithDuration(1.0,
animations:
self.view.frame.origin.y += (self.KeyPadHytVal),
completion: nil)



override func viewDidDisappear(animated: Bool)

super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
view.endEditing(true)
ChkKeyPadDspVar = false




|::| Sometimes View wil be down, In that case use height +/- 150 :


NonKeyPadAraVar.size.height -= self.KeyPadHytVal + 150

self.view.frame.origin.y -= self.KeyPadHytVal - 150,
completion: nil)

self.view.frame.origin.y += self.KeyPadHytVal - 150,
completion: nil)


func keyboardWillShow(notification: NSNotification)

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
self.view.frame.origin.y = self.view.frame.height - (self.view.frame.height + keyboardSize.height)




func keyboardWillHide(notification: NSNotification)
self.view.frame.origin.y = 0



it must be more stable


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)



// MARK: - keyboard
func keyboardWillShow(notification: NSNotification)


if let userInfo = notification.userInfo
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
let contentInsets = self.tblView.contentInset as UIEdgeInsets
self.tblView.contentInset = UIEdgeInsets(top: contentInsets.top, left: contentInsets.left, bottom: keyboardSize.height, right:contentInsets.right)
// ...
else
// no UIKeyboardFrameBeginUserInfoKey entry in userInfo

else
// no userInfo dictionary in notification



func keyboardWillHide(notification: NSNotification)

let contentInsets = self.tblView.contentInset as UIEdgeInsets
self.tblView.contentInset = UIEdgeInsets(top: contentInsets.top, left: contentInsets.left, bottom: 0, right:contentInsets.right)



Use following code for view Up on UITextField Clicked


func textFieldDidBeginEditing(textField: UITextField)
ViewUpanimateMoving(true, upValue: 100)

func textFieldDidEndEditing(textField: UITextField)
ViewUpanimateMoving(false, upValue: 100)

func ViewUpanimateMoving (up:Bool, upValue :CGFloat)
var durationMovement:NSTimeInterval = 0.3
var movement:CGFloat = ( up ? -upValue : upValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(durationMovement)
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()



I made a cocoapod to simplify the matter:



https://github.com/xtrinch/KeyboardLayoutHelper



How to use it:



Make an auto layout bottom constraint, give it a class of KeyboardLayoutConstraint in module KeyboardLayoutHelper and the pod will do the work necessary to increase it to accomodate appearing and disappearing keyboard. See example project on examples how to use it (I made two: textFields inside a scrollView, and vertically centered textFields with two basic views - login & register).



The bottom layout constraint can be of the container view, the textField itself, anything, you name it.


func registerForKeyboardNotifications()

//Keyboard
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWasShown), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIKeyboardDidHideNotification, object: nil)



func deregisterFromKeyboardNotifications()

NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)


func keyboardWasShown(notification: NSNotification)

let userInfo: NSDictionary = notification.userInfo!
let keyboardInfoFrame = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue()

let windowFrame:CGRect = (UIApplication.sharedApplication().keyWindow!.convertRect(self.view.frame, fromView:self.view))

let keyboardFrame = CGRectIntersection(windowFrame, keyboardInfoFrame!)

let coveredFrame = UIApplication.sharedApplication().keyWindow!.convertRect(keyboardFrame, toView:self.view)

let contentInsets = UIEdgeInsetsMake(0, 0, (coveredFrame.size.height), 0.0)
self.scrollViewInAddCase .contentInset = contentInsets;
self.scrollViewInAddCase.scrollIndicatorInsets = contentInsets;
self.scrollViewInAddCase.contentSize = CGSizeMake((self.scrollViewInAddCase.contentSize.width), (self.scrollViewInAddCase.contentSize.height))


/**
this method will fire when keyboard was hidden

- parameter notification: contains keyboard details
*/
func keyboardWillBeHidden (notification: NSNotification)

self.scrollViewInAddCase.contentInset = UIEdgeInsetsZero
self.scrollViewInAddCase.scrollIndicatorInsets = UIEdgeInsetsZero






Use above code to move the textfield above the keyboard in swift 2.2 it will work’s fine . i hope it will help some one
– Kamalkumar.E
Aug 16 '16 at 13:20



swift 3.0 insert in viewDidLoad(), this->





view.addSubview(Your_messageInputConteinerView)


view.addConstraintWithFormat(format: "H:



func handleKeyboardNotification(notification:Notification)


if let userInfo = notification.userInfo

if let keyBoardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue

print(keyBoardFrame)

if bottomConstraint?.constant != CGFloat(0)
bottomConstraint?.constant = 0
return

bottomConstraint?.constant = -keyBoardFrame.height
or
self.view.frame.origin.y = -keyBoardFrame.height






Swift 3 code


var activeField: UITextField?

override func viewDidLoad()
super.viewDidLoad()

NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ProfileViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)


func textFieldDidBeginEditing(_ textField: UITextField)
activeField = textField


func textFieldDidEndEditing(_ textField: UITextField)
activeField = nil


func keyboardWillShow(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if (self.activeField?.frame.origin.y)! >= keyboardSize.height
self.view.frame.origin.y = keyboardSize.height - (self.activeField?.frame.origin.y)!
else
self.view.frame.origin.y = 0




func keyboardWillHide(notification: NSNotification)
self.view.frame.origin.y = 0



i've read answers and solved my problem by this lines of code:


class ViewController: UIViewController, UITextFieldDelegate

@IBOutlet weak var titleField: UITextField!
@IBOutlet weak var priceField: UITextField!
@IBOutlet weak var detailsField: UTtextField!

override func viewDidLoad()
super.viewDidLoad()
// Do not to forget to set the delegate otherwise the textFieldShouldReturn(_:)
// won't work and the keyboard will never be hidden.
priceField.delegate = self
titleField.delegate = self
detailsField.delegate = self

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
name: NSNotification.Name.UIKeyboardWillHide, object: nil)


func textFieldShouldReturn(_ textField: UITextField) -> Bool
self.view.endEditing(true)
return false


func keyboardWillShow(notification: NSNotification)
var translation:CGFloat = 0
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if detailsField.isEditing
translation = CGFloat(-keyboardSize.height)
else if priceField.isEditing
translation = CGFloat(-keyboardSize.height / 3.8)


UIView.animate(withDuration: 0.2)
self.view.transform = CGAffineTransform(translationX: 0, y: translation)




func keyboardWillHide(notification: NSNotification)
UIView.animate(withDuration: 0.2)
self.view.transform = CGAffineTransform(translationX: 0, y: 0)





I have a few UITextFields and want the view to move up differently depending on which textField is tapped.



if you are like me who has tried all the above solutions and still your problem is not solved, I have a got a great solution for you that works like a charm. First I want clarify few things about some of solutions mentioned above.


func keyboardWillHide(notification: NSNotification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
if self.view.frame.origin.y != 0
// self.view.frame.origin.y += keyboardSize.height
self.view.frame.origin.y = 0





Simpelst Method In Swift 4
enter image description here


import UIKit

class ViewController: UIViewController, UITextFieldDelegate

@IBOutlet var myTextField: UITextField!

override func viewDidLoad()
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
myTextField.resignFirstResponder()


func keyboardWillShow(notification: NSNotification)
// let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey]
// print("duration",duration)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
let keyboardHeight : Int = Int(keyboardSize.height)
print("keyboardWillShow",keyboardHeight)
if let height = UserDefaults.standard.value(forKey: "keyboardHeight") as? (Int)
moveTextField(myTextField, moveDistance: -height as Int, moveDuration: 0.43, up: true)
else
UserDefaults.standard.set(keyboardHeight, forKey: "keyboardHeight")
moveTextField(myTextField, moveDistance: -keyboardHeight, moveDuration: 0.43, up: true)




func keyboardWillHide(notification: NSNotification)
if let height = UserDefaults.standard.value(forKey: "keyboardHeight") as? (Int)
moveTextField(myTextField, moveDistance: -height as Int, moveDuration: 0.25, up: false)



func textFieldShouldReturn(_ textField: UITextField) -> Bool
textField.resignFirstResponder()
return true


func moveTextField(_ textField: UITextField, moveDistance: Int, moveDuration: Double, up: Bool)
let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance)
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(moveDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()





You Can Also Move Up And Down Only UITextFiled Not Whole Screen(UIView).

With Using This Method.


UITextFiled


NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil)



And


@objc func keyboardWillChange(notification: NSNotification)

let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y

UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations:
self.textField.frame.origin.y+=deltaY

,completion: nil)



I've need to move a UIView in swift 4 when keyboard opens and closes. and all of the answers couldn't help me. because height of keyboard changes when emojis open. so my code is :


UIView


@objc func keyboardWillShow(sender: NSNotification)

if let keyboardFrame: NSValue = sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue

let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height

if(self.oldHeight == keyboardHeight)
self.sendingView.frame.origin.y -= keyboardHeight
self.oldHeight = keyboardHeight

else
self.sendingView.frame.origin.y += self.oldHeight
self.sendingView.frame.origin.y -= keyboardHeight
self.oldHeight = keyboardHeight




@objc func keyboardWillHide(sender: NSNotification)

if let keyboardFrame: NSValue = sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue

let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height

self.sendingView.frame.origin.y += keyboardHeight





and in viewDidLoad() :


viewDidLoad()


NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);



self.oldHeight = CGFloat() and defines as field at the top of class.


self.oldHeight = CGFloat()






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard