I have a login page which has two textviews and a button in a stackView I'm trying to move the stackview when the keyboard shows and also disappears as I want to know how to do this programmatically
Asked
Active
Viewed 66 times
2 Answers
-1
iOS sends 2 notifications when keyboard will show/hide
UIKeyboardWillShow
UIKeyboardWillHide
What you can do, is observe those notifications, and move the frame of your stackView such as
@objc func keyboardWillShow() {
if stackView.frame.origin.y == 0 {
stackView.frame.origin.y -= 200
}
}
@objc func keyboardWillHide() {
if stackView.frame.origin.y != 0 {
stackView.frame.origin.y = 0
}
}
And here is how to observe those notification. (use this code in your viewDidLoad function)
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)

Alexandre Odet
- 372
- 2
- 13
-
I added that code but get this error, Type 'Notification.Name' (aka 'NSNotification.Name') has no member 'UIResponder' – farooq Mar 11 '20 at 11:36
-
Notification name is UIViewController.keyboardWillShow and UIViewController.keyboardWillHide. Can you try ? – Alexandre Odet Mar 11 '20 at 12:35
-
That works, but now its saying Use of unresolved identifier 'stackView' it won't let me access the stackView when I'm using the if statement – farooq Mar 11 '20 at 12:52
-
Remplace "stackView" with the name of your actual stack view... – Alexandre Odet Mar 12 '20 at 13:24
-1
Swift 4.2
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIWindow.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIWindow.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
print("keyboardWillShow")
}
@objc func keyboardWillHide(notification: NSNotification){
print("keyboardWillHide")
}
If still got any error check below link:

Shubhendu Devmurari
- 159
- 14