Resize the screen when keyboard appears

move view up when keyboard appears ios swift 4
how to show keyboard on screen in swift
move button when keyboard appears swift
scroll textview when keyboard appears swift
move uitableview up when keyboard appears
scroll uitableview when keyboard appears swift
scroll view up when keyboard appears ios
move scrollview up when keyboard appears ios swift

I am building a chat app. I have to move a textfield when keyboard appears. I am doing this with the following code:

func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let keyboardSize =  (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            kbHeight = keyboardSize.height
            self.animateTextField(true)
        }
    }
}
func keyboardWillHide(notification: NSNotification) {
    self.animateTextField(false)
}

func animateTextField(up: Bool) {
    var movement = (up ? -kbHeight : kbHeight)

    UIView.animateWithDuration(0.3, animations: {
        self.view.frame = CGRectOffset(self.view.frame, 0, movement)
    })
}

But when I use this code, the first messages doesn't show. I guess I have to resize the tableview.

Here are screenshots Before and After the keyboard appears:

I am using auto layout.

How can I resolve this problem?

Resize the screen when keyboard appears, I have to move a textfield when keyboard appears. I am doing this with the following code: func keyboardWillShow(notification: NSNotification) { if let userInfo� In storyboard. Select your search bar. At the corner in the lower right you'll see 3 icons. Click the middle one looking like |-[]-| . At the top of that popup, there are 4 boxes. Enter 0 at the one for the bottom. Constraint created!

2020 UPDATE
There is only one way to properly handle this mess in iOS.
  1. Paste KUIViewController below in to your project,

  2. Create a constraint which is very simply to the "bottom of your content". Discussed below.

  3. Drag that constraint to bottomConstraintForKeyboard

KUIViewController will automatically and correctly resize your content view at all times.

Absolutely everything is totally automatic.

All Apple behaviors are handled correctly, such as dismissing by taps, etc etc.

You're done.

So "which view should you resize?"

You can not use .view ...

Because ... you cannot resize the .view in iOS!!!!!! Doh!

Simply make a UIView named "holder". It sits inside .view.

Put everything of yours inside "holder".

Holder will of course have four simple constraints top/bottom/left/right to .view.

That bottom constraint to "holder" is indeed bottomConstraintForKeyboard.

You're done.

Send a bill to the cliient and go drinking.

There is nothing more to do. class KUIViewController: UIViewController {

    // KBaseVC is the KEYBOARD variant BaseVC. more on this later

    @IBOutlet var bottomConstraintForKeyboard: NSLayoutConstraint!

    @objc func keyboardWillShow(sender: NSNotification) {
        let i = sender.userInfo!
        let s: TimeInterval = (i[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let k = (i[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
        bottomConstraintForKeyboard.constant = k
        // Note. that is the correct, actual value. Some prefer to use:
        // bottomConstraintForKeyboard.constant = k - bottomLayoutGuide.length
        UIView.animate(withDuration: s) { self.view.layoutIfNeeded() }
    }

    @objc func keyboardWillHide(sender: NSNotification) {
        let info = sender.userInfo!
        let s: TimeInterval = (info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        bottomConstraintForKeyboard.constant = 0
        UIView.animate(withDuration: s) { self.view.layoutIfNeeded() }
    }

    @objc func clearKeyboard() {
        view.endEditing(true)
        // (subtle iOS bug/problem in obscure cases: see note below
        // you may prefer to add a short delay here)
    }

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

    override func viewDidLoad() {
        super.viewDidLoad()
        keyboardNotifications()
        let t = UITapGestureRecognizer(target: self, action: #selector(clearKeyboard))
        view.addGestureRecognizer(t)
        t.cancelsTouchesInView = false
    }
}

Simply ...

Use KUIViewController anywhere a keyboard might appear.
class AddCustomer: KUIViewController, SomeProtocol {

class CustomerPicker: KUIViewController {

On those screens absolutely everything is now completely automatic.

You're done.

Phew.


*Minor footnote - background clicks correctly dismiss the keyboard. That includes clicks which fall on your content. This is correct Apple behavior. Any unusual variation from that would take a huge amount of very anti-Apple custom programming.

*Minor footnote - so, any and all buttons on the screen will work 100% correctly every time. However in some VERY obscure cases of nested (!) container views inside nested (!) scroll views with nested (!) page view containers, you may find that a button will seemingly not work, i.e. it will not call it's touch up action. This seems to be essentially a bug or some subtle behavior chain problem in current iOS. If you encounter this problem, fortunately the solution is simple. Looking at the function clearKeyboard() which just dismisses the keyboard, simply add a short delay.

@objc func clearKeyboard() {
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
        self.view.endEditing(true)
    }
}

(In fact, I always just leave the delay code in, since it's harmless and I like the feel anyway. And if you have a crazy nested scrolling page view container, you'll have no trouble with any buttons. This great tip from user @wildcat12 https://stackoverflow.com/a/57698468/294884 )

Swift 3 and iOS: Resizing the scroll view on keyboard appearance, If the content of your view isn't big enough to fit the size of the screen when the keyboard appears, much of your content will be off screen. You can use a scroll� Initially, I suggest you to press and hold on a corner of the On-Screen Keyboard and drag to resize it. As far as the grayed out options is concerned, let us try updating Windows and check for the issue.

From @Fattie 's message:

A detail - (unfortunately) clicks on your content will also dismiss the keyboard. (They both get the event.) However, this is almost always correct behavior; give it a try. There is no reasonable was to avoid this, so forget about it and go with the Apple-flow.

This can be solved by implementing the following UIGestureRecognizerDelegate's method:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        return !(touch.view?.isKind(of: UIControl.self) ?? true)
    }

That way, if the user touches any UIControl (UIButton, UITextField, etc.) the gesture recognizer won't call the clearKeyboard() method.

For this to work, remember to subclass UIGestureRecognizerDelegate either at class definition or with an extension. Then, in viewDidLoad() you should assign the gesture recognizer delegate as self.


Ready to copy and paste code:

// 1. Subclass UIGestureRecognizerDelegate
class KUIViewController: UIViewController, UIGestureRecognizerDelegate {

@IBOutlet var bottomConstraintForKeyboard: NSLayoutConstraint!

func keyboardWillShow(sender: NSNotification) {
    let i = sender.userInfo!
    let k = (i[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
    bottomConstraintForKeyboard.constant = k - bottomLayoutGuide.length
    let s: TimeInterval = (i[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    UIView.animate(withDuration: s) { self.view.layoutIfNeeded() }
}

func keyboardWillHide(sender: NSNotification) {
    let info = sender.userInfo!
    let s: TimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    bottomConstraintForKeyboard.constant = 0
    UIView.animate(withDuration: s) { self.view.layoutIfNeeded() }
}

func keyboardNotifications() {
    NotificationCenter.default.addObserver(self,
        selector: #selector(keyboardWillShow),
        name: Notification.Name.UIKeyboardWillShow,
        object: nil)
    NotificationCenter.default.addObserver(self,
        selector: #selector(keyboardWillHide),
        name: Notification.Name.UIKeyboardWillHide,
        object: nil)
}

func clearKeyboard() {
    view.endEditing(true)
}

override func viewDidLoad() {
    super.viewDidLoad()
    keyboardNotifications()
    let t = UITapGestureRecognizer(target: self, action: #selector(clearKeyboard))
    view.addGestureRecognizer(t)
    t.cancelsTouchesInView = false

    // 2. Set the gesture recognizer's delegate as self
    t.delegate = self
}

// 3. Implement this method from UIGestureRecognizerDelegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    return !(touch.view?.isKind(of: UIControl.self) ?? true)
}
}

Handle input method visibility, For example, when the vertical space on the screen is constrained, the attached hardware keyboard, the soft input method does not appear. Below are the steps for resizing a window only using the keyboard. Press Alt+Space to open the window menu. If the window is maximized, arrow down to Restore and press Enter, then press Alt+Space bar again to open the window menu. Arrow down to Size.

if you don't want to fight with this yourself you might find the TPKeyboardAvoiding framework useful

Simply just following the 'installation instructions' i.e. drag and drop the appropriate .h/.m files into your project and then make you ScrollView / TableView a subclass like below:

Keyboard Handling on Android, The default behavior when the Android soft keyboard appears on the screen is for resizing your application layout when the soft keyboard is being shown that� It allows you to use the keyboard and a menu called the system or control menu to move or resize a window. Normally, this little-used menu can be opened by clicking on the icon in the upper left corner of a window but there is also a keyboard shortcut to open it. Enter the keyboard combination Alt+Space Bar.

Maybe it will help somebody. You can achieve the desired behavior without using interface builder at all

First of all you will need to create a constraint and calculate safe area insets in order to support buttonless devices properly

var container: UIView!
var bottomConstraint: NSLayoutConstraint!
let safeInsets = UIApplication.shared.windows[0].safeAreaInsets

then initialize it somewhere in your code

container = UIView()
bottomConstraint = container.bottomAnchor.constraint(equalTo: view.bottomAnchor)

attach it to view and activate

view.addSubview(container)

NSLayoutConstraint.activate([
       ...

       container.leadingAnchor.constraint(equalTo: view.leadingAnchor),
       container.trailingAnchor.constraint(equalTo: view.trailingAnchor),
       container.topAnchor.constraint(equalTo: view.topAnchor),
       bottomConstraint,

       ...
 ])

and finally

@objc func keyboardWillShow(notification: NSNotification) {
       if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

       if bottomConstraint.constant == 0 {
          bottomConstraint.constant = -keyboardSize.height + safeInsets.bottom     
          view.layoutIfNeeded()
       }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
       bottomConstraint.constant = 0
       view.layoutIfNeeded()
}

Also if your view is something scrollable and you want to move it up with keyboard and return to initial position as the keyboard hides, you can change view's contentOffset

view.contentOffset = CGPoint(x: view.contentOffset.x, y: view.contentOffset.y + keyboardSize.height - safeInsets.bottom)

for scrolling up, and

view.contentOffset = CGPoint(x: view.contentOffset.x, y: view.contentOffset.y - keyboardSize.height + safeInsets.bottom)

to move it down

Use the floating keyboard on your iPad, Then you can change the keyboard back to its full size. Touch and hold the gray line to move the keyboard on your screen. To use QuickPath� The touch keyboard was changed with the Fall Creators Edition update. It now displays in a much larger area -- it takes up nearly half of the screen when the "full" keyboard is selected, both when the keyboard is locked to the bottom of the screen or when it can be moved to another position.

Android: Resize only parts of view with soft keyboard on screen, How to move the layout up when the soft keyboard is shown android , use android:windowSoftInputMode="adjustPan". "adjustResize". The activity's main� Become a Patron of Ask Leo!and go ad-free! Normally, of course, you can resize a window by using the mouse and clicking on and dragging the border of the window. In a case like this, though, the border is off the screen, and there’s no way to move the mouse over to click on it. The result is that we have to use the keyboard interface.

How to prevent Soft Keyboard from resizing background image, How to adjust layout when soft-keyboard appear in android to move up so that if there is enough screen space they are shown above the keyboard, or to make� The icons in the top-right corner allow you to move or enlarge the keyboard. The keyboard button at the bottom of the on-screen keyboard allows you to select different layouts. There’s also a more advanced on-screen keyboard, which is part of the Ease of Access settings.

Avoid resizing PageView children when keyboard shows up � Issue , Avoid resizing PageView children when keyboard shows up #30494 the PageView resizes to match the remaining screen space, even when it was otherwise whenever the keyboard appears the inner widget will resize. But what happens if you also want to adjust more controls than just the entries, like images, buttons, etc. This is a common use case when we are developing a Login screen, if we want to always show the Login button even when keyboard shows up. Let’s do it step by step. Doing this is a bit different depending on the platform.

Comments
  • Are you using auto layout in your storyboard?
  • Yes, I am using auto layout.
  • Oh!... I forgot that... sorry.
  • don't update the frame, update the contentInset.
  • stackoverflow.com/questions/48922266/…
  • Second solution doesn't work. It doesn't do anything. I think I have to use first solution but I need more info for creating bottom constraint.
  • Textbox shows up under the keyboard, do you know how can I move it?
  • The inset won't be applied to the text box so you'll probably have to use the constraints instead. If it's just the table view, then changing the inset would be enough. Is this text box inside a table view cell?
  • instead of hardcoding the animation duration 0.5 you should use the provided length info[UIKeyboardAnimationDurationUserInfoKey]. There are sometimes where the change happens without animation
  • Updated the code for Swift 3. @JoeBlow: I don't think an (old) answer should be voted down just because it hasn't been updated to the latest version of the language. You could either leave a comment or edit the answer correcting the minor changes and be done with it (instead of replacing the full post). I think it's an insult to people who have been putting lots of effort and time in helping others and the community by down voting a perfect valid answer just because it's not up to date to the latest version.
  • You know, this should not be so hard!
  • This is the best answer i have found, very nice. Although it seems to move up too much for me, seems to be the same size of the tab bar.