I'm trying to get my app to move the view when the keyboard appears, and so far the results have been... mixed to say the least. I can get it to move, thing is it's either hard coded or only works partially.
I have multiple Textfields in my view, when I tap on them, sometimes depending on where my scroll is it get's hidden by the keyboard.
Now what I need my app to do is to move the view to see the textfield only if the active textfield is hidden by the keyboard.
My Hierarchy for the view goes like this :
So I have a Scroll view, and in the scroll View I have a UIView named ContentView, in the ContentView I have all my textfields and labels.
thing is, I can't hard code it since My app is universal, I need to have the keyboard move the view only if it hides the textfield. Because in a situation where the user is on an iPad, the View will likely never have to move
I used the following Stack overflow answers with no results :
Swift: Scroll View only when a TextField or Button is hidden by the Keyboard
Move view with keyboard using Swift
here's my code that actually comes from one of those answers :
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NewPaxController.keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NewPaxController.keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification:NSNotification) {
if keyboardIsPresent == false {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.ContentView.frame.origin.y -= keyboardSize.height
keyboardIsPresent = true
}
}
}
func keyboardWillHide(notification:NSNotification) {
if keyboardIsPresent == true {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.ContentView.frame.origin.y += keyboardSize.height
keyboardIsPresent = false
}
}
}
I'm almost 100% sure all my error come from the fact the I have a ContentView... but I need it in my case. Thanks in advance for your help