Move view with keyboard using Swift

250,629

Solution 1

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?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
        self.view.frame.origin.y -= keyboardSize.height
    }            
}

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

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

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

func keyboardWillHide(notification: NSNotification) {
    if view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

Swift 3.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?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }        
}

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}
    

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?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }        
}

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

Swift 4.2:

override func viewDidLoad() {
    super.viewDidLoad()            
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

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

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

Solution 2

Easiest way that doesn't even require any code:

  1. Download KeyboardLayoutConstraint.swift and add (drag & drop) the file into your project, if you're not using the Spring animation framework already.
  2. In your storyboard, create a bottom constraint for the View or Textfield, select the constraint (double-click it) and in the Identity Inspector, change its class from NSLayoutConstraint to KeyboardLayoutConstraint.
  3. Done!

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

Solution 3

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.

Solution

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

Remove Observers

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

Solution 4

Not an advertisement or promotion or spam, just a good solution. I know that this question has nearly 30 answers and I'm so shocked that no one even mentioned once about this beautiful GitHub project that does it all for you and even better. All the answers just move the view upwards. I just solved all my problems with this IQKeyboardManager. It has 13000+ stars.
Just add this in your podfile if you are using swift

pod 'IQKeyboardManagerSwift'

and then inside your AppDelegate.swift do import IQKeyboardManagerSwift

import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

      IQKeyboardManager.shared.enable = true // just add this line

      return true
    }
}

Add the line IQKeyboardManager.shared.enable = true to enable it
This solution is a must if you are going for production.

Solution 5

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: UIResponder.keyboardWillChangeFrameNotification, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

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

func keyboardWillChange(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] 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: UIResponder.keyboardWillChangeFrameNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
Share:
250,629
Alex Catchpole
Author by

Alex Catchpole

Full Stack Engineer at WalkIn

Updated on September 08, 2021

Comments

  • Alex Catchpole
    Alex Catchpole almost 3 years

    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.

  • DannieCoderBoi
    DannieCoderBoi over 9 years
    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. :(
  • user3677173
    user3677173 over 9 years
    You can use UIView.animateWithDuration(1.0, animations: { self.view.frame.origin.y -= 150 }, completion: nil)
  • Teodor Ciuraru
    Teodor Ciuraru over 9 years
    It might not work with "Auto-Layout" so consider deactivating it if so.
  • Mike
    Mike about 9 years
    It causes some funky behavior with autolayout @Josh, you are mistaken
  • Mike
    Mike about 9 years
    If you are using auto layout, make sure to call self.view.setTranslatesAutoresizingMaskIntoConstraints(true) before you move in up and self.view.setTranslatesAutoresizingMaskIntoConstraints(false‌​) before you move it back
  • Josh
    Josh about 9 years
    @Mike It works here and I'm happy, obviously, I am not mistaken. Funky things are the daily water and bread of xCode. I am no iOS expert, so I cannot debate more than what my eyes see. For the record, I am using Xcode 6.3 and autolayout. and building to iOS 8.3
  • V_J
    V_J about 9 years
    Its not working for me. The screen goes black after moving from one UITextField to other.
  • user3677173
    user3677173 about 9 years
    It depends on a layout. Constraints can mess up with frames.
  • nielsbot
    nielsbot over 8 years
    Don't do this! You cannot assume the keyboard is a certain size.
  • Mugunthan Balakrishnan
    Mugunthan Balakrishnan over 8 years
    when dealing with multiple text fields, the view keeps moving up and does not come back down
  • Dan Beaulieu
    Dan Beaulieu over 8 years
    You're going to have to change your conditions to account for the text fields
  • Mugunthan Balakrishnan
    Mugunthan Balakrishnan over 8 years
    thanks for the response, i found the answer i was looking for at this thread on stack overflow stackoverflow.com/questions/1126726/…
  • Dan Beaulieu
    Dan Beaulieu over 8 years
    @MugunthanBalakrishnan thanks for bringing this up, I've added a solution.
  • jonprasetyo
    jonprasetyo over 8 years
    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
  • ML.
    ML. over 8 years
    This is a great solution except in one case. I am having issues when transitioning from a regular keyboard to a number pad. I am getting a black screen.
  • iluvatar_GR
    iluvatar_GR over 8 years
    @Matthew Lin use a boolean so the functions keyboardWillShow and hide only works one time
  • SwingerDinger
    SwingerDinger about 8 years
    Don't forget to set the Delegate to the textFields
  • Stephen Horvath
    Stephen Horvath about 8 years
    Any idea why all the UI elements disappear when I use becomeFirstResponder() with this? The elements move up with the keyboard and then disappear after the animation stops.
  • gammachill
    gammachill about 8 years
    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/…
  • xtrinch
    xtrinch almost 8 years
    Should use keyboardSize. What happens when you have accessory views and different keyboard heights on devices? Detached keyboard?
  • KingofBliss
    KingofBliss almost 8 years
    Change the condition in keyboardwillshow as, if (!CGRectContainsPoint(aRect, newOrgin!) && !self.viewWasMoved)
  • KingofBliss
    KingofBliss almost 8 years
    add self.viewWasMoved = false when u resetting the frame
  • bearacuda13
    bearacuda13 almost 8 years
    @Boris This is only a solution if the user has a perfectly simple plain keyboard. If the user unmerges the keyboard into two sections, it screws up the view.
  • Kamalkumar.E
    Kamalkumar.E almost 8 years
    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
  • yesthisisjoe
    yesthisisjoe over 7 years
    Works great for the stock keyboard, but doesn't pick up the height of custom keyboards.
  • Vandan Patel
    Vandan Patel over 7 years
    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.
  • Brian Bird
    Brian Bird over 7 years
    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
  • Tarvo Mäesepp
    Tarvo Mäesepp over 7 years
    How you deal with multiple textFields? E.G if you want to do it only on one textField?
  • Virendra Singh Rathore
    Virendra Singh Rathore about 7 years
    Shouldn't i remove this observers on view disappears func?
  • ajayb
    ajayb almost 7 years
    The code doesn't work well for custom keyboards. My keyboard's height does not compute properly on first run. Is there a fix for the code to take in consideration the height of custom keyboards?
  • Noor Dawod
    Noor Dawod almost 7 years
    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
  • Will Mays
    Will Mays almost 7 years
    This works good but can you get it to move depending on where the textfield is if you have multiple ones instead of moving one to fit them all
  • miguelSantirso
    miguelSantirso almost 7 years
    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.
  • Masih
    Masih over 6 years
    this solution works better than accepted answer. Accepted answer shows the keyboard only once which to me is a bug :)
  • Masih
    Masih over 6 years
    this is buggy, it moves the view only once, better solution here: stackoverflow.com/a/46366394/4995771
  • reza_khalafi
    reza_khalafi over 6 years
    Why just work one time? when keyboard dismiss and for second time tap on textfield keyboard not move up. I checked it and I find out for second time keyboard.height size in KyboardWillShow method is zero(0). why???
  • jshapy8
    jshapy8 over 6 years
    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.
  • Ahmadreza
    Ahmadreza over 6 years
    My tab bar is also moving up with window! :(
  • Arnab
    Arnab over 6 years
    Please replace UIKeyboardFrameBeginUserInfoKey with UIKeyboardFrameEndUserInfoKey. First one gives start frame of the keyboard, which comes zero sometimes, while second one gives the end frame of the keyboard.
  • rudald
    rudald over 6 years
    Hi guys, there is a bug. The observers are not removed from the view after being called in viewWillDisappear. Replace this line "NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: self.view.window)" with "NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)" then observer is removed
  • Clifton Labrum
    Clifton Labrum almost 6 years
    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?
  • Saeed Ir
    Saeed Ir almost 6 years
    It's better to use UIKeyboardFrameEndUserInfoKey for new third parties keyboards
  • Joel
    Joel almost 6 years
    Welcome to SO! When posting code in your answer, it is important to explain why your code works or how it solves OP's problem :)
  • Ankur Lahiry
    Ankur Lahiry almost 6 years
    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.
  • Achraf
    Achraf almost 6 years
    if anyone having trouble with the frame going down when changing textFields, you may disable autocorrection !
  • jeet.chanchawat
    jeet.chanchawat over 5 years
    This code is again broken with notch based devices :(
  • elarcoiris
    elarcoiris over 5 years
    Hi sir, could you please tell me why this doesn't work when placed in a view that also contains a TableView? It works fine in the same scenario when it contains a CollectionView.
  • Sarthak Mishra
    Sarthak Mishra over 5 years
    The only modification i made was to change the code in "keyboardWillHide" where the origin is assigined to this self.view.frame.origin.y = 0
  • Chief Madog
    Chief Madog over 5 years
    this sulotion has allot of issues, ive tried it in my app, and it's doing allot of problems especialy once u move between one textfield to another
  • rene
    rene over 5 years
    Very good! (In viewDidLoad you have "VehiculeViewController" instead of just "ViewController").
  • YoanGJ
    YoanGJ over 5 years
    I had to use UIResponder.keyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey as it was not recognized in Swift 4.2
  • zeeshan
    zeeshan over 5 years
    This works for Xcode 10.1 and iOS 12. The accepted answer is not valid any longer.
  • Matthew Knippen
    Matthew Knippen over 5 years
    On Notch based devices (iPhone X, XS, XS Max, XR), this code will not work. I would highly suggest using @SarthakMishra's advice and setting self.view.frame.origin.y = 0. This then matches the check in the method above
  • Ely Dantas
    Ely Dantas over 5 years
    If you have centered views, set priority 750 in Y axis and than add a KeyboardLayoutConstraint subclassed bottom constraint.
  • ScottyBlades
    ScottyBlades over 5 years
    This was an awesome answer. Very cool design as well. One suggestion: If your textviews/textfields are on table view cells you might notice the views that have this constraint will jump awkwardly every time the user clicks enter and goes to the next text field. You can wrap the animations in DispatchQueue.main.async {} to fix it. Good work! Thumbs up!
  • Joshua Wolff
    Joshua Wolff over 5 years
    I tried this exact solution and found that 6 memory leaks result when the user taps to view the keyboard for the first time after launching app. Memory is not leaked thereafter. I get 6 leaks, and the backtrace mentions UIKeyboardPredictonView as one of the leaked objections. I found this using Apple's Profiler, and I observe the 6 leaks using both UIKeyboardFrameBeginUserInfoKey and UIKeyboardFrameEndUserInfoKey. I also did not use a flag as @johnprasetyo suggests.
  • Munib
    Munib over 5 years
    This is an excellent answer, the only thing I would add is keeping track of the bottom safe area in the newer devices (X, XS, etc) so that it accounts for that.
  • Antzi
    Antzi over 5 years
    @Munib See stackoverflow.com/a/54993623/1485230 Other issues include the view not animating, and keyboard height change not being followed.
  • ChrisO
    ChrisO over 5 years
    Why does this have to be so hard? All I want to do is shift my app up when the keyboard appears. There are a million different answers on stackoverflow and all of them seem to have edge cases that don't work correctly.
  • Edison
    Edison over 5 years
    This does not fix the black area where the keyboard was on the iPhone X and newer. And every time the keyboard appears and disappears the main view keeps sliding down.
  • Samira
    Samira over 5 years
    What if we also have some text fields in the upper half of the view I know this solution works only if textfields are in the lower half of the view I wonder what if we have a list of text fields from up to bottom in a view
  • Ben
    Ben about 5 years
    A much more complete and useful answer. Thank you! I suggest that the keyboard check is called as follows because it will give a consistent size of the keyboard.........if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfo‌​Key] as? NSValue)?.cgRectValue.size
  • btrballin
    btrballin about 5 years
    Awesome answer, but I have a special case where I have a table view with a cell containing the text area, so it's pushing the table view upward but not the whole cell
  • Warpzit
    Warpzit about 5 years
    THIS WILL NOT WORK. What if the user uses split mode or undock? What about the free floating keyboard comming out with ios 13? Don't do it.
  • Saifan Nadaf
    Saifan Nadaf about 5 years
    what if my textField is top of the view..? i mean if there is textfield with origin Y = 0..?? then textField is going up and i cant see it
  • Saifan Nadaf
    Saifan Nadaf about 5 years
    what if my textField is top of the view..? i mean if there is textfield with origin Y = 0..?? then textField is going up and i cant see it
  • Saifan Nadaf
    Saifan Nadaf about 5 years
    what if my textField is top of the view..? i mean if there is textfield with origin Y = 0..?? then textField is going up and i cant see it
  • Saifan Nadaf
    Saifan Nadaf about 5 years
    what if my textField is top of the view..? i mean if there is textfield with origin Y = 0..?? then textField is going up and i cant see it
  • Neph
    Neph almost 5 years
    @CliftonLabrum I've got the same problem and because of this one of my buttons has its height decreased automatically (decribed here). :/ Did you manage to find a solution for this?
  • Dhanu K
    Dhanu K almost 5 years
    This is really good, but the latest version doesn't work for me, I have used 6.2.1, and import as import IQKeyboardManager and used IQKeyboardManager.shared().isEnabled = true in AppDelegate
  • Dhanu K
    Dhanu K almost 5 years
    And this works awesomely when using multiple edit texts, This saved my time
  • zeeshan
    zeeshan almost 5 years
    Can't thank enough for pointing out to this wonderful library. This library is finally THE FINAL ANSWER to all keyboard related nonsense which Apple has never provided a solution for. Now I'll be using it for all my projects, new and old, and save time and headache which this keyboard appearing, disappearing or not disappearing, or how to hide it, and why it is overlapping, issues have been causing me since the day I am programming for iPhones.
  • iphaaw
    iphaaw almost 5 years
    This is the best answer. tbl should be tableView and I added some padding: contentInset.bottom = keyboardFrame.size.height + 10
  • anoop4real
    anoop4real almost 5 years
    I have found one issue the observer doesnt get removed, the deinit in the class never gets called... i tried to add the class programatically
  • Darren
    Darren over 4 years
    This looked like the best solution, however there are a couple of bugs. 1, the textfield moves up but when I start typing in it it jumps up a little more. 2, In landscape when typing the textField sometimes jumps to the left.
  • adougies
    adougies about 4 years
    @DhanuK, Just found this library and works perfectly and it's effortless. The app delegate code has been updated to IQKeyboardManager.shared.enable = true
  • Saifan Nadaf
    Saifan Nadaf about 4 years
    @Darren i am trying to figure out these bugs but i haven't found, can you please tell where you got these bugs i mean for which version/device...??
  • KZoNE
    KZoNE about 4 years
    The proper solution, Thanks!! Is there any specific way to catch each tap on text fields and push up the screen in different sizes?
  • Ethan Brimhall
    Ethan Brimhall about 4 years
    This was the best answer. None of the other solutions worked for me except this one!
  • J.C
    J.C about 4 years
    This answer needs to be higher, much higher.
  • T.E.
    T.E. over 3 years
    Is there an update for swift 5, or will the code under Swift 4.2 work properly?
  • Amit Samant
    Amit Samant over 3 years
    @CliftonLabrum replace updateContraint function with swift func updateConstant() { let safeAreaBottom = UIApplication.appDelegate.window?.safeAreaInsets.bottom ?? 0 let height: CGFloat if keyboardVisibleHeight > 0 { height = keyboardVisibleHeight - safeAreaBottom } else { height = 0 } self.constant = offset + height } also, I have convenience accessor for app delegate which gave my window if you are on ios 13 make sure you get the window object from you scenedelegate
  • xhinoda
    xhinoda over 3 years
    Work on XCode 12.2 and Swift 5, nice!
  • NDQuattro
    NDQuattro about 3 years
    In my case initial self.view.frame.origin.y wasn't 0.
  • J A S K I E R
    J A S K I E R about 3 years
    Top safe area. Don't forget to add this or remove each time. Each device has it's own.
  • Wahab Khan Jadon
    Wahab Khan Jadon almost 3 years
    I am already using this but when the keyboard collapse the view doest move back to its original position... IQKeyboardManager.shared.layoutIfNeededOnUpdate = true adding this line also, resolve my issue ...
  • Yisus
    Yisus over 2 years
    Works really great, but when I use it in a UIView that is contained in a UIViewController nested in UITabBarController the UIView moves up and never returns down. Maybe i'm missing something. Any comment or help is welcome.
  • Saifan Nadaf
    Saifan Nadaf over 2 years
    @Yisus can you please share a demo, so that i can check easily ?
  • Yisus
    Yisus over 2 years
    @SaifanNadaf after a few days I solved my problem. I think that the problem comes from a weird implementation of NavigationBar in my legacy project. I set the 'isTranslucent' property to false. It was moving up my view away from my bottom. Thanks any way.
  • Kian
    Kian over 2 years
    Note that for this to work properly, the first item of the constraint has to be the reference point in the view (e.g. Superview.Bottom) and the second item has to be the bottom of the view or textfield or whatever. If you have it the other way around then the view/textfield moves down instead of up when the keyboard appears.
  • oskarko
    oskarko over 2 years
    This should be the accepted answer! It's the best one at all!!
  • Mohammad Bashir Sidani
    Mohammad Bashir Sidani over 2 years
    this is pure genius
  • Mr. T.
    Mr. T. about 2 years
    best answer for this problem of iOS. i've been trying to find something like this for 15mins and here it is!