1

I have an issue with my application. I am actually building a login page and I do not find how to handle the keyboard when a text field is active. I have two text fields in a view. In my superView, I have 3 views. One on the bottom, another on the middle and a last on top. The 3 views are embeded in a stack view.

I really want to shrink the stack view, in other words reduce the space between all 3 views only when the keyboard appears and set the size back when the keybaord disappear, like Facebook login page on iOS.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
EdwinJr__
  • 7
  • 4

1 Answers1

0

You need to subscribe to keyboard notifications and do this in viewDidLoad

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

//

@objc func keyboardWillShow(notification: NSNotification) {
   self.stackV.spacing = 10
    UIView.animate(withDuration: 0.3, animations: { () -> Void in
        self.view.layoutIfNeeded()
    })
}

@objc func keyboardWillHide(notification: NSNotification) {
    self.stackV.spacing = // set back to default
    UIView.animate(withDuration: 0.3, animations: { () -> Void in
        self.view.layoutIfNeeded()
    })
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Thank you very much for your help. The problem is that my stack view distribution is set to equal spacing, thus my spacing value is set to 0 by default. Do you think I should take off my views from the stack view and manually add animations? – EdwinJr__ Jun 17 '18 at 15:34
  • see hook the height constraint of the stackView and change it or it's bottom constraint – Shehata Gamal Jun 17 '18 at 15:37
  • I just tried it a few minutes ago, but it do not work. I think I should embed each view in a stack view and embed each stack in a big stack. Then it will be easier to shrink? – EdwinJr__ Jun 17 '18 at 15:55