172

I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom. When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen. I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those.

Is there a way to have the screen only move when the bottom fields are edited?

I have used this code I found here:

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(sender: NSNotification) {
    self.view.frame.origin.y -= 150
}

func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 150
}
Vaisakh KP
  • 467
  • 1
  • 6
  • 25
John Allijn
  • 1,945
  • 3
  • 12
  • 9
  • may be you could use func textFieldDidBeginEditing(textField: UITextField!) { } to detect which textfield has started editing and do keyboard hide/ show – humblePilgrim Mar 02 '15 at 15:32
  • I forgot to mention that I am new to Swift :( What would be the correct syntax to check this? (how do I get the field name in this function?) – John Allijn Mar 02 '15 at 16:56

25 Answers25

226

Your problem is well explained in this document by Apple. Example code on this page (at Listing 4-1) does exactly what you need, it will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew. The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:

Declare a variable

var activeField: UITextField?

then add these methods

 func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.scrollEnabled = true
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeFieldPresent = activeField
    {
        if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
        {
            self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
        }
    }


}


func keyboardWillBeHidden(notification: NSNotification)
{
    //Once keyboard disappears, restore original positions
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.scrollEnabled = false

}

func textFieldDidBeginEditing(textField: UITextField!)
{
    activeField = textField
}

func textFieldDidEndEditing(textField: UITextField!)
{
    activeField = nil
}

Be sure to declare your ViewController as UITextFieldDelegate and set correct delegates in your initialization methods: ex:

self.you_text_field.delegate = self

And remember to call registerForKeyboardNotifications on viewInit and deregisterFromKeyboardNotifications on exit.

Edit/Update: Swift 4.2 Syntax

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}
Tyler927
  • 197
  • 1
  • 12
Nerkyator
  • 3,976
  • 1
  • 25
  • 31
  • Nerkyator could you elaborate a little more on registerForKeyboardNotifications? Where, when and why would I call this method? Thanks – PeonProgrammer Mar 02 '15 at 17:37
  • 3
    You have to call registerForKeyboardNotifications at viewDidLoad, so you will add an observer to notification center for when keyboard appears or disappears from screen. When these notification fire, methods keyboardWasShown and keyboardWillBeHidden will be called and then scrollview will move accordingly to keyboard size. You can find more detailed information about NotificationCenter here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/ – Nerkyator Mar 02 '15 at 20:47
  • Find activeTextField with: `private func findActiveTextField (subviews : [UIView], inout textField : UITextField?) { for view in subviews { if let tf = view as? UITextField where view.isFirstResponder() { textField = tf break } else if !view.subviews.isEmpty { findActiveTextField (view.subviews, textField: &textField) } } }` – John Slade Nov 24 '15 at 00:01
  • 13
    Thanks, that's exactly what I was looking for - an apple recommended solution. However, in my case I already had a scroll view that spanned outside the viewable area. This code would disable scrolling after the keyboard would hide. I removed "self.scrollView.scrollEnabled = false" and it would still not scroll. What worked for me was "self.scrollView.contentInset = UIEdgeInsetsZero;" this single line in keyboardWillHide event – F Yaqoob Feb 06 '16 at 19:12
  • for code in objective C http://code.tutsplus.com/tutorials/ios-sdk-keeping-content-from-underneath-the-keyboard--mobile-6103 – mars Mar 02 '16 at 09:53
  • I like this solution (swift3), but I have one problem with it. I use the decimalPad keyboard - which, OOTB does not come with a 'Done' / 'Next' button, so I used code from another thread to add one in a bar just above the keyboard. Doing so increases the height of area being obscured by the keyboard and causes the view to *not* scroll when the field is above the keyboard but behind the 'done bar'. I tried several things in the code, but cannot figure out how to make it adjust for that additional height. Suggestions? – Adam Stoller Oct 25 '16 at 15:19
  • I figured out part of my issue. I added `let height = (keyboardSize?.height)! + 50` and then used `height` where applicable. Unfortunately, now that it scrolls the view when the first field becomes obscured, when firstResponder is transferred from *that* field to the *next* field (below it), the textfield's frame data comes from it being in a scrolled-up position - it fails the 'is-obscured' test, and it then scrolls the view back down... obscuring the field. – Adam Stoller Oct 25 '16 at 15:58
  • If you are using textVIEWS in stackviews - especially stackviews within stackviews, you need to modify the reference to the frame. The scroll to instruction would need to be self.scrollView.scrollRectToVisible(activeTextField.superview.superview.frame, animated: true) or whatever level of embedding you have. – JohnSF Jan 20 '17 at 05:05
  • if your active field is a subview, and not a direct child, use `activeField.convert(activeField.frame.origin, to: self.view)` instead of referencing `activeField.frame.origin` directly when using `aRect.contains()` – haitham Feb 20 '17 at 17:08
  • `if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {` is safer – haitham Feb 20 '17 at 17:10
  • I get this error `Value of type 'ViewController' has no member scrollView` – Siddharth Mar 22 '17 at 10:58
  • I get the same error as @Siddharth, that my viewController has no member Scroll View, someone has solved it? – Mago Nicolas Palacios Apr 18 '17 at 20:24
  • Interesting error here. Kept crashing until I changed the name of the `textFieldDid...` functions to `txtFieldDid...` And @Siddharth, you just have to add an outlet connected to your view controller called scrollView, mine reads `@IBOutlet var scrollView: UIScrollView!` ... ALSO, this was an interesting read: https://www.natashatherobot.com/ios-autolayout-scrollview/ – Meshach Apr 20 '17 at 00:55
  • Value ViewController has no member `scrollview` – grantespo Apr 25 '17 at 05:46
  • If you have several text fields that could be active, consider using a computed property `activeField` – averydev May 01 '17 at 23:54
  • 7
    Perfect code. But I need to use `UIKeyboardFrameEndUserInfoKey` instead of `UIKeyboardFrameBeginUserInfoKey`, because the latter return height 0. And change the hittest point to the bottom not origin. `if let activeField = self.activeField { var point = activeField.frame.origin point.y += activeField.frame.size.height if (!aRect.contains(point)){ self.scrollView.scrollRectToVisible(activeField.frame, animated: true) } }` – Victor Choy Aug 28 '17 at 10:43
  • 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. – Arnab Mar 02 '18 at 12:26
  • The function `keyboardWillBeHidden` is being executed but the `UIScrollView` doesn't scroll back to its original position. Does anybody have the same problem? – Rod Mar 15 '18 at 13:52
  • Might also need to add something like: let realPosition = activeField.superview?.convert(activeField.frame.origin, to: nil) – Witterquick Mar 20 '18 at 07:15
  • is this still the recommended way to do this as of swift4 / ios11 ? – MaX Apr 18 '18 at 09:22
  • 3
    @MaX: It should work, but if you want a Swift4 solution you can check [this iOS example](https://github.com/mattneub/Programming-iOS-Book-Examples/blob/swift4ios11/bk2ch10p522textFieldScrollView/ch23p805textFieldSliding/ViewController.swift) from [Matt Neuburg](https://stackoverflow.com/users/341994/matt)'s book that I suggest to all iOS developers :) – Nerkyator Apr 18 '18 at 10:04
  • @Nerkyator thx! I looked into that and tried it on my device. unfortunately it is a bit laggy i.e. not smooth in transitioning. basically first the keyboard appear and then after it the view moves. it is certainly not smooth at all like in some messaging app where the keyboard appears at the same time you either scroll or the view moves because of tapping a textfield (e.g. Facebook's messenger). any way how to do this? – MaX Apr 19 '18 at 02:07
  • uhm, quite strange because this is basically the correct way how to handle keyboard appearing on screen. I tried it on many devices and simulators and never noticed lag :\ – Nerkyator Apr 19 '18 at 12:19
  • @Nerkyator I was finally able to implement it by using the code from this post and adapting it to swift 4 manually (as I said the one from the book is lagging for me). the only thing that bothers me is that sometimes the `keyboardWasShown` method doesn't fire (i.e the print I put there doesn't run), even if the keyboard has been invoked. this results in the view not shifting up. do you perhaps know what could be causing it? – MaX May 09 '18 at 06:25
  • 3
    @MaX I'm not sure if this exclusively a swift 4 thing, but what seems to be happening is that the `textField's didBeginEditing` method is called AFTER the `keyboardWillShow` method was called. As a result, the `activeField` variable is still nil, which means no automatic scrolling happens. My solution was to put the `activeField = textField` call in the textField's `shouldBeginEditing` method. This resolves the order of calls issue. – HirdayGupta May 29 '18 at 09:46
  • I also had to adjust the contentSize for this work, `self.scrollView.contentSize = CGSize(width: self.scrollView.frame.width, height: self.scrollView.frame.height)`. For more details: https://stackoverflow.com/questions/1446536/uiscrollview-works-as-expected-but-scrollrecttovisible-does-nothing – Jurgen Sep 23 '21 at 03:12
  • The issue I'm having is that it the scrollview becomes unscrollable after the keyboarad is dismissed. I even removed `self.scrollView.isScrollEnabled = false`, but still - the scroll view becomes unscrollable. Any thoughts? – Landmaster Jan 26 '22 at 12:31
174

Here is My 2 cents:

Have you tried: https://github.com/hackiftekhar/IQKeyboardManager

Extremely easy to install Swift or Objective-C.

Here how it works:

IQKeyboardManager (Swift):- IQKeyboardManagerSwift is available through CocoaPods, to install it simply add the following line to your Podfile: (#236)

pod 'IQKeyboardManagerSwift'

In AppDelegate.swift, just import IQKeyboardManagerSwift framework and enable IQKeyboardManager.

import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

    IQKeyboardManager.sharedManager().enable = true
    // For Swift 4, use this instead
    // IQKeyboardManager.shared.enable = true


    return true
    }
}

And that is all. Easy!

truthsayer
  • 397
  • 2
  • 8
  • 22
Mr H
  • 5,254
  • 3
  • 38
  • 43
  • 22
    Perfect. This should be built in by default. Seems ridiculous that it's not. – NathofGod Apr 20 '16 at 08:08
  • 1
    This is actually ridiculous, its so easy to implement and just works, plus you get an easy way to toggle through multiple text fields – Khoury Nov 02 '16 at 03:38
  • toggling into multiple text fields wouldn't work ? no arrow display on keypad to move between textfields. – Arsal Apr 04 '17 at 18:48
  • 1
    This was an amazing solution, thank you! It took me a little bit of work to get the CocoaPods set up correctly, as those were entirely new to me. After I had that set up, it was literally 2 lines of code to implement this and it worked perfectly right off the bat. Thanks so much! – IcyBlueRose Apr 06 '17 at 16:50
  • Mostly works (Swift 3.0 - XCODE 8+) however, the first time click on a textfield, the entire view is scrolled upwards off the view. Any one else experiencing this use case? – Jeeves May 22 '17 at 06:56
  • This didn't seem to work for projects that didn't want to use that enhanced toolbar that they add to the keyboard -every time I removed it - it broke things like autocompleting fields and dropdowns. Would be useful to have a simplified version of this pod – UKDataGeek Jul 15 '17 at 23:58
  • Using Xcode 9 but just coding using Swift 3.3 (I want to be iOS10 compatible for now) and it works just fine with the version 5.0.0 this saved me a big headache, thank you – Pedro Cavaleiro Oct 09 '17 at 19:17
  • @Jeeves I am facing same issue like you. Have you found any solution? – Zalak Patel Nov 29 '17 at 07:11
  • For those coming here for Xamarin: https://www.nuget.org/packages/Xamarin.IQKeyboardManager/ – Mike Richards May 09 '18 at 14:05
  • 6
    This did not work for me in Swift 4.1 IQKeyboardManager.sharedManager().enable = true **Has been switched to** `IQKeyboardManager.shared.enable = true` – Rmalmoe Jun 27 '18 at 23:21
  • Just use the sample code in the official setup instructions instead of the sample code in this answer. It's more up-to-date. – Andrew Koster Jul 18 '19 at 23:31
  • Amazing, I'm never-ever going to make another app without this. Ridiculously easy, works great and I just cannot believe that the State of the Art doesn't include this out of the box honestly – blastervla Apr 07 '20 at 03:07
  • I won't recommend this package as it's not actively maintained and there are already many bugs within the package – Joshua Aug 09 '21 at 09:15
21

The one I found to work perfectly for me was this:

func textFieldDidBeginEditing(textField: UITextField) {
    if textField == email || textField == password {
        animateViewMoving(true, moveValue: 100)
    }
}

func textFieldDidEndEditing(textField: UITextField) {
    if textField == email || textField == password {
        animateViewMoving(false, moveValue: 100)
    }
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
    let movementDuration:NSTimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)

    UIView.beginAnimations("animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration)

    self.view.frame = CGRectOffset(self.view.frame, 0, movement)
    UIView.commitAnimations()
}

You can also change the height values. Remove the "if statement" if you want to use it for all text fields.

You can even use this for all controls that require user input like TextView.

Jayprakash Dubey
  • 35,723
  • 18
  • 170
  • 177
Edward
  • 2,291
  • 2
  • 19
  • 33
  • 5
    Moving a UIView frame directly is not a great solution. Additionally this includes hardcoded values that are specific to this use case. I would encourage people to not implement a solution like this and instead do something that is closer to best practices as described in the accepted answer. – MobileVet Sep 15 '16 at 20:52
  • @MobileVet Understood, but this is the one that works. – Tarvo Mäesepp Jan 28 '17 at 16:23
  • amazing separate logic without changing in to our code – Dilip Jangid Mar 29 '17 at 09:37
8

Is there a way to have the screen only move when the bottom fields are edited?

I had a similar problem and found a pretty straightforward solution without using a scrollView, and instead using if statements within the keyboardWillShow/Hide methods.

func keyboardWillShow(notification: NSNotification) {
    if bottomText.editing{
        self.view.window?.frame.origin.y = -1 * getKeyboardHeight(notification)
    }
}

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

This was a good solution for me because I only had two text fields.

Shifts whole view up: only when certain text fields (bottomText) are edited

Shifts whole view down: only when the view is not at the original location

Phil Hudson
  • 3,819
  • 8
  • 35
  • 59
villejacob
  • 89
  • 1
  • 5
6

Just use this extension to move any UIView when keyboard is presented.

extension UIView {
    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc func keyboardWillChange(_ notification: NSNotification){
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let beginningFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let endFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

        let deltaY = endFrame.origin.y - beginningFrame.origin.y

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

Then in your viewdidload bind your view to the keyboard

UiView.bindToKeyboard()
Vaisakh KP
  • 467
  • 1
  • 6
  • 25
Bilal Mustafa
  • 230
  • 3
  • 12
  • This moves the view up even if it is not needed and if the textfield is at the top of view it will go up and will not be visible. This is not a good solution. – Shivam Pokhriyal Aug 31 '18 at 18:27
  • The code needs to be updated, here is the fix https://stackoverflow.com/questions/52316676/type-nsnotification-name-has-no-member-keyboarddidshownotification – Gaurav Rai Nov 30 '20 at 04:43
  • This works for me! But it's updated some details – Zhming Oct 02 '22 at 18:47
4

Why not implement this in a UITableViewController instead? The keyboard won't hide any text fields when its shown.

RJiryes
  • 951
  • 10
  • 25
  • this is actually the easiest and the most robust way. And it works even with controls which use a custom InputView instead of the default keyboard (UIKeyboard notifications don't work for these) – Radu Simionescu Sep 08 '15 at 07:32
  • 1
    There is the problem that you have to be careful, if the table view is embedded (rather than being "the whole page"). For anyone tripped up by that, the solution is explained in posts like [this](http://stackoverflow.com/questions/594181/making-a-uitableview-scroll-when-text-field-is-selected/24085537#24085537) and [this](http://stackoverflow.com/questions/594181/making-a-uitableview-scroll-when-text-field-is-selected/6165256#6165256). Hope it helps someone dealing with the "most utterly stupid problem in all of Apple" ! – Fattie Dec 06 '16 at 15:44
4

Swift 4 (**updated) with extension**

  1. add the buttons in one container
  2. connect bottom constraint of the container with IBOutlet containerBtmConstrain
  3. inViewDidLoad

    self.containerDependOnKeyboardBottomConstrain = containerBtmConstrain
    self.watchForKeyboard() 
    
  4. add the following extension

    import UIKit
    
    private var xoAssociationKeyForBottomConstrainInVC: UInt8 = 0
    
    extension UIViewController {
    
        var containerDependOnKeyboardBottomConstrain :NSLayoutConstraint! {
            get {
                return objc_getAssociatedObject(self, &xoAssociationKeyForBottomConstrainInVC) as? NSLayoutConstraint
            }
            set(newValue) {
                objc_setAssociatedObject(self, &xoAssociationKeyForBottomConstrainInVC, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
            }
        }
    
        func watchForKeyboard() {
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown(notification:)), name:UIResponder.keyboardWillShowNotification, object: nil);
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name:UIResponder.keyboardWillHideNotification, object: nil);
        }
    
        @objc func keyboardWasShown(notification: NSNotification) {
            let info = notification.userInfo!
            guard let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
              return
            }
    
            UIView.animate(withDuration: 0.3, animations: { () -> Void in
                self.containerDependOnKeyboardBottomConstrain.constant = -keyboardFrame.height
                self.view.layoutIfNeeded()
            })
        }
    
        @objc func keyboardWillHide(notification: NSNotification) {
            UIView.animate(withDuration: 0.3, animations: { () -> Void in
                self.containerDependOnKeyboardBottomConstrain.constant = 0
                self.view.layoutIfNeeded()
            })
        }
    }
    
iluvatar_GR
  • 1,017
  • 13
  • 19
  • 1
    Thanks, mate. It's all about the right key. I was using UIKeyboardFrameBeginUserInfoKey and now using UIKeyboardFrameEndUserInfoKey handles it gracefully. – Felipe Sep 21 '17 at 00:21
2

I use SwiftLint, which had a few issues with the formatting of the accepted answer. Specifically:

no space before the colon, no force casting, prefer UIEdgeInset(top: etc... instead of UIEdgeInsetMake.

so here are those updates for Swift 3

func registerForKeyboardNotifications() {
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications() {
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWasShown(notification: NSNotification) {
    //Need to calculate keyboard exact size due to Apple suggestions
    scrollView?.isScrollEnabled = true
    var info = notification.userInfo!
    if let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
        let contentInsets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)

        scrollView?.contentInset = contentInsets
        scrollView?.scrollIndicatorInsets = contentInsets

        var aRect: CGRect = self.view.frame
        aRect.size.height -= keyboardSize.height
        if let activeField = self.activeField {
            if !aRect.contains(activeField.frame.origin) {
                self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
            }
        }
    }
}

func keyboardWillBeHidden(notification: NSNotification) {
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    if let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
        let contentInsets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize.height, right: 0.0)
        scrollView?.contentInset = contentInsets
        scrollView?.scrollIndicatorInsets = contentInsets
    }

    view.endEditing(true)
    scrollView?.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField) {
    activeField = nil
}
2

Swift: You can do this by checking which textField is being presented.

@objc func keyboardWillShow(notification: NSNotification) {
    if self.textField.isFirstResponder == true {
        self.view.frame.origin.y -= 150
     }
}

@objc func keyboardWillHide(notification: NSNotification){
    if self.textField.isFirstResponder == true {
       self.view.frame.origin.y += 150
    }
}
ZAFAR007
  • 3,049
  • 1
  • 34
  • 45
1

I think this clause is wrong:

if (!CGRectContainsPoint(aRect, activeField!.frame.origin))

While the activeField's origin may well be above the keyboard, the maxY might not...

I would create a 'max' point for the activeField and check if that is in the keyboard Rect.

zevij
  • 2,416
  • 1
  • 23
  • 32
1

Since there were no answer on how to do this in Combine, here is the approach i used.

  1. We create a publisher to listen to both Notifications, show and hide.
  2. For show we get the frame of the keyboard from the notifications userInfo and check if the current active responder is contained in it. If it's covered return keyboard frame height. If it is not covered return 0, we don't want to move the frame. For the hide notification we simply return 0.
private var keyboardHeightPublisher: AnyPublisher<CGFloat, Never> {
    Publishers.Merge(
        NotificationCenter.default
            .publisher(for: UIResponder.keyboardWillShowNotification)
            .compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect }
            .map { $0.intersects(self.view.firstResponder!.frame) ? $0.height : 0 }
            .map { $0 * -1 },
        NotificationCenter.default
            .publisher(for: UIResponder.keyboardWillHideNotification)
            .map { _ in CGFloat(0) }
    ).eraseToAnyPublisher()
}

In the viewDidLoad we simply subscribe to the publisher changing the views frame accordingly.

override func viewDidLoad() {
    super.viewDidLoad()

    keyboardHeightPublisher.sink{ [weak self] height in
        self?.view.frame.origin.y = height
    }.store(in: &cancelables)
}

EDIT
Be careful! If the firstResponder is in a subview, you have to calculate the frame corresponding to the whole screen to check if they actually intersect.
Example:

let myViewGlobalFrame = myView.convert(myView.frame, to: parentView)
Deitsch
  • 1,610
  • 14
  • 28
0

Here's my version after reading the documentation provided by Apple and the previous posts. One thing I noticed is that the textView was not handled when covered by the keyboard. Unfortunately, Apple's documentation won't work because, for whatever reason, the keyboard is called AFTER the textViewDidBeginEditing is called. I handled this by calling a central method that checks if the keyboard is displayed AND if a textView or textField is being edited. This way, the process is only fired when BOTH conditions exists.

Another point with textViews is that their height may be such that the keyboard clips the bottom of the textView and would not adjust if the Top-Left point of the was in view. So, the code I wrote actually takes the screen-referenced Bottom-Left point of any textView or textField and sees if it falls in the screen-referenced coordinates of the presented keyboard implying that the keyboard covers some portion of it.

let aRect : CGRect = scrollView.convertRect(activeFieldRect!, toView: nil)
    if (CGRectContainsPoint(keyboardRect!, CGPointMake(aRect.origin.x, aRect.maxY))) {
        // scroll textView/textField into view
    }

If you're using a navigation controller, the subclass also sets the scroll view automatic adjustment for insets to false.

self.automaticallyAdjustsScrollViewInsets = false

It walks through each textView and textField to set delegates for handling

    for view in self.view.subviews {
        if view is UITextView {
            let tv = view as! UITextView
            tv.delegate = self
        } else if view is UITextField {
            let tf = view as! UITextField
            tf.delegate = self
        }
    }

Simply set your base class to the subclass created here for results.

import UIKit

class ScrollingFormViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {

var activeFieldRect: CGRect?
var keyboardRect: CGRect?
var scrollView: UIScrollView!

override func viewDidLoad() {

    self.automaticallyAdjustsScrollViewInsets = false

    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.registerForKeyboardNotifications()
    for view in self.view.subviews {
        if view is UITextView {
            let tv = view as! UITextView
            tv.delegate = self
        } else if view is UITextField {
            let tf = view as! UITextField
            tf.delegate = self
        }
    }
    scrollView = UIScrollView(frame: self.view.frame)
    scrollView.scrollEnabled = false
    scrollView.showsVerticalScrollIndicator = false
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.addSubview(self.view)
    self.view = scrollView
}

override func viewDidLayoutSubviews() {
    scrollView.sizeToFit()
    scrollView.contentSize = scrollView.frame.size
    super.viewDidLayoutSubviews()
}

deinit {
    self.deregisterFromKeyboardNotifications()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ScrollingFormViewController.keyboardWasShown), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ScrollingFormViewController.keyboardWillBeHidden), name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    let info : NSDictionary = notification.userInfo!
    keyboardRect = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
    adjustForKeyboard()
}


func keyboardWillBeHidden(notification: NSNotification)
{
    keyboardRect = nil
    adjustForKeyboard()
}

func adjustForKeyboard() {
    if keyboardRect != nil && activeFieldRect != nil {
        let aRect : CGRect = scrollView.convertRect(activeFieldRect!, toView: nil)
        if (CGRectContainsPoint(keyboardRect!, CGPointMake(aRect.origin.x, aRect.maxY)))
        {
            scrollView.scrollEnabled = true
            let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardRect!.size.height, 0.0)
            scrollView.contentInset = contentInsets
            scrollView.scrollIndicatorInsets = contentInsets
            scrollView.scrollRectToVisible(activeFieldRect!, animated: true)
        }
    } else {
        let contentInsets : UIEdgeInsets = UIEdgeInsetsZero
        scrollView.contentInset = contentInsets
        scrollView.scrollIndicatorInsets = contentInsets
        scrollView.scrollEnabled = false
    }
}

func textViewDidBeginEditing(textView: UITextView) {
    activeFieldRect = textView.frame
    adjustForKeyboard()
}

func textViewDidEndEditing(textView: UITextView) {
    activeFieldRect = nil
    adjustForKeyboard()
}

func textFieldDidBeginEditing(textField: UITextField)
{
    activeFieldRect = textField.frame
    adjustForKeyboard()
}

func textFieldDidEndEditing(textField: UITextField)
{
    activeFieldRect = nil
    adjustForKeyboard()
}

}
0

Awesome answers are already given but this is a different way to deal with this situation (using Swift 3x):

First of all call the following method in viewWillAppear()

func registerForKeyboardNotifications() {

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

}

Now take one IBOutlet of UIView's top constraints of your UIViewcontroller like this: (here the UIView is the subview of UIScrollView that means you should have a UIScrollView for all your subViews)

@IBOutlet weak var loginViewTopConstraint: NSLayoutConstraint!

And an another variable like following and add a delegate i.e. UITextFieldDelegate:

var activeTextField = UITextField() //This is to keep the reference of UITextField currently active

After that here is the magical part just paste this below snippet:

func keyboardWasShown(_ notification: Notification) {

let keyboardInfo  = notification.userInfo as NSDictionary?

//print(keyboardInfo!)

let keyboardFrameEnd: NSValue? = (keyboardInfo?.value(forKey: UIKeyboardFrameEndUserInfoKey) as? NSValue)

let keyboardFrameEndRect: CGRect? = keyboardFrameEnd?.cgRectValue


if activeTextField.frame.origin.y + activeTextField.frame.size.height + 10 > (keyboardFrameEndRect?.origin.y)! {

    UIView.animate(withDuration: 0.3, delay: 0, options: .transitionFlipFromTop, animations: {() -> Void in

        //code with animation

        //Print some stuff to know what is actually happening
        //print(self.activeTextField.frame.origin.y)
        //print(self.activeTextField.frame.size.height)
        //print(self.activeTextField.frame.size.height)

        self.loginViewTopConstraint.constant = -(self.activeTextField.frame.origin.y + self.activeTextField.frame.size.height - (keyboardFrameEndRect?.origin.y)!) - 30.0

        self.view.layoutIfNeeded()

    }, completion: {(_ finished: Bool) -> Void in
        //code for completion

    })
}
}

func keyboardWillBeHidden(_ notification: Notification) {

UIView.animate(withDuration: 0.3, animations: {() -> Void in

    self.loginViewTopConstraint.constant = self.view.frame.origin.y
    self.view.layoutIfNeeded()

})
}

//MARK: textfield delegates
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    activeTextField = textField
    return true
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

           switch textField {
    case YOUR_TEXTFIELD_ONE:
        YOUR_TEXTFIELD_TWO.becomeFirstResponder()
        break
    case YOUR_TEXTFIELD_TWO:
        YOUR_TEXTFIELD_THREE.becomeFirstResponder()
        break
    default:
        textField.resignFirstResponder()
        break
    }
    return true
}

Now the last snippet:

//Remove Keyboard Observers
override func viewWillDisappear(_ animated: Bool) {

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

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

Don't forget to assign delegates to all your UITextFields in UIStoryboard

Good luck!

Anurag Sharma
  • 4,276
  • 2
  • 28
  • 44
0

Swift 3 syntax:

func textFieldDidBeginEditing(_ textField: UITextField) {
    // add if for some desired textfields
        animateViewMoving(up: true, moveValue: 100)
}

func textFieldDidEndEditing(_ textField: UITextField) {
    // add if for some desired textfields
        animateViewMoving(up: false, moveValue: 100)
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
     textFieldDidEndEditing(_ textField: UITextField) {

    let movementDuration:TimeInterval = 0.5

    let movement:CGFloat = ( up ? -moveValue : moveValue)

    UIView.beginAnimations("animateView", context: nil)

    UIView.setAnimationBeginsFromCurrentState(true)

    UIView.setAnimationDuration(movementDuration)

    self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)

    UIView.commitAnimations()
}

this is a nice method to get what you want you can add "if" conditions for certain textfields but this type works for all... Hope it can be useful for everyone

Atrin Noori
  • 311
  • 3
  • 12
0

First of all declare a variable to identify your active UITextField.

Step 1:-

Like as var activeTextField: UITextField?

Step 2:- After this add these two lines in viewDidLoad.

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)

Step 3:-

Now define these two methods in your controller class.

func keyboardWillShow(_ notification: NSNotification) {

    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}


func keyboardWillHide(_ notification: NSNotification) {

    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = true
}


func textFieldDidBeginEditing(_ textField: UITextField){

    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){

    activeField = nil
}
Juan Serrats
  • 1,358
  • 5
  • 24
  • 30
0

for swift 4.2.

This will apply to any form. No need of scrollview. do not forget to set delegate.

Make a var of uitextfield

var clickedTextField = UITextField()

In your viewdid load

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

Know the clicked text field. probably you are having textfields on the entire screen.

func textFieldDidBeginEditing(_ textField: UITextField) {
    clickedTextField = textField
}

Check if the keyboard is covering textfield or not.

@objc func keyboardWillShow(sender: NSNotification,_ textField : UITextField) {
    if let keyboardSize = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

        if clickedTextField.frame.origin.y > keyboardSize.origin.y {
            self.view.frame.origin.y = keyboardSize.origin.y - clickedTextField.center.y - 20
        }
    }
}

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

Return to close keyboard

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
    textField.resignFirstResponder()
    return true
}

UPDATE : NSNotification.Name.UIKeyboardWillShow & NSNotification.Name.UIKeyboardWillHide are renamed to UIResponder.keyboardWillShowNotification & UIResponder.keyboardWillHideNotification respectively.

Community
  • 1
  • 1
rupesh45
  • 125
  • 2
  • 8
  • lets say you have taken an outlet of usernameTextfield in your viewController. In viewDidLoad just write : usernameTextField.delegate = self – rupesh45 Sep 21 '20 at 08:17
  • 1
    Thanks for for info. I've followed this to the letter and it does not lift up the keyboard. I've played around with the code, but cannot get it to work. I'm using iOS 14 and Xcode 12. Thanks. – David_2877 Sep 21 '20 at 17:32
  • Did you confirm the UITextViewDelegate protocol to uiviewcontroller ? if this is not working then you can use "IQKeyboardManager" library. – rupesh45 Sep 22 '20 at 08:27
-1

Swift 3

@IBOutlet var scrollView: UIScrollView!
@IBOutlet var edtEmail: UITextField!
@IBOutlet var bottomTextfieldConstrain: NSLayoutConstraint! // <- this guy is the constrain that connect the bottom of textField to lower object or bottom of page!

 @IBAction func edtEmailEditingDidBegin(_ sender: Any) { 
        self.bottomTextfieldConstrain.constant = 200
        let point = CGPoint(x: 0, y: 200)
        scrollView.contentOffset = point
    }

@IBAction func edtEmailEditingDidEnd(_ sender: Any) { 
    self.bottomTextfieldConstrain.constant = 50
}
Ahmadreza
  • 6,950
  • 5
  • 50
  • 69
-1

The accepted anwser is nearly perfect. But I need to use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey, because the latter return keyborad height 0. And change the hittest point to the bottom not origin.

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        var point = activeField.frame.origin
        point.y += activeField.frame.size.height
        if (!aRect.contains(point)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
Victor Choy
  • 4,006
  • 28
  • 35
-1

Swift 4 Updated my solution

with constraint animation on keyboard show/hide, enjoy.

import Foundation
import UIKit

class PhoneController: UIViewController, UITextFieldDelegate{

    var phoneLayoutYConstraint: NSLayoutConstraint?

    override func viewDidLoad() {

        super.viewDidLoad()

        view.backgroundColor = .white

        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        phoneField.delegate = self

        view.addSubview(phoneField)

        NSLayoutConstraint.activate([phoneField.heightAnchor.constraint(equalToConstant: 50),
                                     phoneField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
                                     phoneField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
                                     phoneField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)])

        phoneLayoutYConstraint = NSLayoutConstraint(item: phoneField, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
        phoneLayoutYConstraint?.isActive = true

    }

    let phoneField: UITextField = {
        let text = UITextField()
        text.translatesAutoresizingMaskIntoConstraints = false
        text.keyboardType = .numberPad
        text.font = UIFont.systemFont(ofSize: 30)
        text.layer.cornerRadius = 5.0
        text.layer.masksToBounds = true
        text.layer.borderColor = UIColor.darkGray.cgColor
        text.layer.borderWidth = 2.0

        return text
    }()


    override func viewDidDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

    }


    func textFieldDidEndEditing(_ textField: UITextField) {

    }

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


   @objc func handleKeyBoardNotification(_ notification: NSNotification) {

        if let info = notification.userInfo {

            let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
            let isKeyBoardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow

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


            phoneLayoutYConstraint?.constant = isKeyBoardShowing ? -keyboardSize!.height : 0

            UIView.animate(withDuration: 0, delay: 0, options: .curveEaseOut, animations: {
                self.view.layoutIfNeeded()
            }, completion: { (boo) in

            })

        }
    }

}
Hattori Hanzō
  • 2,349
  • 4
  • 19
  • 36
-1

Swift 4

You Can Easily Move Up And Down UITextField With Keyboard With Animation

enter image description here

import UIKit

class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil)
    }

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

    @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)
    }
ZAFAR007
  • 3,049
  • 1
  • 34
  • 45
-1

Swift 4.2

My solution will (vertically) center the view on a UITextField if its position is under the keyboard.

Step 1: Create new swift file and copy-paste UIViewWithKeyboard class.
Step 2: In Interface Builder set it as a Custom Class for your top most UIView.

import UIKit

class UIViewWithKeyboard: UIView {
    @IBInspectable var offsetMultiplier: CGFloat = 0.75
    private var keyboardHeight = 0 as CGFloat
    private weak var activeTextField: UITextField?
    override func awakeFromNib() {
        super.awakeFromNib()
        NotificationCenter.default.addObserver(self, selector: #selector(UIViewWithKeyboard.textDidBeginEditing),
                                               name: UITextField.textDidBeginEditingNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(UIViewWithKeyboard.keyboardWillShow),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(UIViewWithKeyboard.keyboardWillHide),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    @objc func textDidBeginEditing(_ notification: NSNotification) {
        self.activeTextField = notification.object as? UITextField
    }

    @objc func keyboardWillShow(_ notification: Notification) {
        if let frameValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
            keyboardHeight = frameValue.cgRectValue.size.height
            if let textField = self.activeTextField {
                let offset = textField.frame.maxY < frame.maxY - keyboardHeight ? 0
                           : textField.frame.maxY - (frame.maxY - keyboardHeight) * offsetMultiplier
                self.setView(offset: offset)
            }
        }
    }

    @objc func keyboardWillHide(_ notification: NSNotification) {
        self.setView(offset: 0)
    }

    func setView(offset: CGFloat) {
        UIView.animate(withDuration: 0.25) {
            self.bounds.origin.y = offset
        }
    }
}
scope
  • 1,967
  • 14
  • 15
-1

Rewritten for swift 4.2

In ViewDidLoad..

 NotificationCenter.default.addObserver(self, selector: #selector(trailViewController.keyboardWasShown), name: UIResponder.keyboardWillShowNotification, object: nil)
 NotificationCenter.default.addObserver(self, selector: #selector(trailViewController.keyboardWillBeHidden), name: UIResponder.keyboardWillHideNotification, object: nil)

Remaining Funtions

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}
VarunRaj
  • 142
  • 1
  • 7
-2

"I forgot to mention that I am new to Swift :( What would be the correct syntax to check this? (how do I get the field name in this function?) "

Ok . First confirm to the UITextFieldDelegate protocol

class YourClass:UITextFieldDelegate

Then implement the function

func textFieldDidBeginEditing(textField: UITextField!) {

    if textField == txtOne
    {
        println("TextOne")
    }
    if textField == txtTwo
    {
        println("TextTwo")
    }
}

You should note that the proper approach is to use a scrollview and place the view that should be shifted up/down inside the scroll view and handle keyboard events accordingly

humblePilgrim
  • 1,818
  • 4
  • 25
  • 47
-2

This code moves up the text field you are editing so that you can view it in Swift 3 for this answer you also have to make your view a UITextFieldDelegate:

var moveValue: CGFloat!
var moved: Bool = false
var activeTextField = UITextField()

func textFieldDidBeginEditing(_ textField: UITextField) {
    self.activeTextField = textField
}
func textFieldDidEndEditing(_ textField: UITextField) {
    if moved == true{
    self.animateViewMoving(up: false, moveValue: moveValue )
        moved = false
    }
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
    let movementDuration:TimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)

    UIView.beginAnimations("animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration)

    self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
    UIView.commitAnimations()
}

And then in viewDidLoad:

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

Which calls (outside viewDidLoad):

func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardSize.height
        if (view.frame.size.height-self.activeTextField.frame.origin.y) - self.activeTextField.frame.size.height < keyboardHeight{
            moveValue = keyboardHeight - ((view.frame.size.height-self.activeTextField.frame.origin.y) - self.activeTextField.frame.size.height)
            self.animateViewMoving(up: true, moveValue: moveValue )
            moved = true
        }
    }
}
joshLor
  • 1,034
  • 1
  • 12
  • 27
-6

For Swift 4.2

This code will allow you to control the Y axis moment of the frame for a specific device screen size.

PS: This code will not intelligently move the frame based on the location of TextField.

Create an extension for UIDevice

extension UIDevice {
    enum ScreenType: String {
        case iPhone4_4S = "iPhone 4 or iPhone 4s"
        case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE"
        case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6s, iPhone 7 or iPhone 8"
        case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6s Plus, iPhone 7 Plus or iPhone 8 Plus"
        case iPhoneX_Xs = "iPhone X, iPhone Xs"
        case iPhoneXR = "iPhone XR"
        case iPhoneXSMax = "iPhone Xs Max"
        case unknown
    }
    var screenType: ScreenType {
        switch UIScreen.main.nativeBounds.height {
        case 960:
            return .iPhone4_4S
        case 1136:
            return .iPhones_5_5s_5c_SE
        case 1334:
            return .iPhones_6_6s_7_8
        case 1920, 2208:
            return .iPhones_6Plus_6sPlus_7Plus_8Plus
        case 1792:
            return .iPhoneXR
        case 2436:
            return .iPhoneX_Xs
        case 2688:
            return .iPhoneXSMax
        default:
            return .unknown
        }
    }
}

Add NotificationObserver on 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)

Selector

@objc func keyboardWillShow(notification: NSNotification) {
    if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        if self.view.frame.origin.y == 0 {
            switch (UIDevice.current.screenType.rawValue) {
            case (UIDevice.ScreenType.iPhones_5_5s_5c_SE.rawValue):
                self.view.frame.origin.y -= 210
            case (UIDevice.ScreenType.iPhones_6_6s_7_8.rawValue):
                self.view.frame.origin.y -= 110
            case (UIDevice.ScreenType.iPhones_6Plus_6sPlus_7Plus_8Plus.rawValue):
                self.view.frame.origin.y -= 80
            case (UIDevice.ScreenType.iPhoneX_Xs.rawValue):
                self.view.frame.origin.y -= 70
            case (UIDevice.ScreenType.iPhoneXR.rawValue):
                self.view.frame.origin.y -= 70
            case (UIDevice.ScreenType.iPhoneXSMax.rawValue):
                self.view.frame.origin.y -= 70
            default:
                self.view.frame.origin.y -= 150
            }
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        if self.view.frame.origin.y != 0 {
            switch (UIDevice.current.screenType.rawValue) {
            case (UIDevice.ScreenType.iPhones_5_5s_5c_SE.rawValue):
                self.view.frame.origin.y += 210
            case (UIDevice.ScreenType.iPhones_6_6s_7_8.rawValue):
                self.view.frame.origin.y += 110
            case (UIDevice.ScreenType.iPhones_6Plus_6sPlus_7Plus_8Plus.rawValue):
                self.view.frame.origin.y += 80
            case (UIDevice.ScreenType.iPhoneX_Xs.rawValue):
                self.view.frame.origin.y += 70
            case (UIDevice.ScreenType.iPhoneXR.rawValue):
                self.view.frame.origin.y += 70
            case (UIDevice.ScreenType.iPhoneXSMax.rawValue):
                self.view.frame.origin.y += 70
            default:
                self.view.frame.origin.y += 150
            }
        }
    }
}
Kavin Varnan
  • 1,989
  • 18
  • 23
  • 1
    In general I would say it is a bad and rather costly approach to use device specific types and hardcode layout related dimensions as they keep changing. – Johan Jan 17 '20 at 15:13