I have textFields that I'd like to move down to just above the keyboard when I'm editing.
When the keyboard appears my views origin is pushed up by a distance equivalent the height of the keyboard, then what I want to do next is scroll my scrollView down so the textField that is being edited lays right above the keyboard. I can get the view to change origin but I can't seem to get the scroll view to scroll down. What I've tried to do is calculate the distance between the top of the keyboard and the textField being edited. That distance gives me a height and a way to calculate a y-cord to create a rect so I can call scrollRectToVisible
.
So to make it clear, I create a rect right above the textField with a height equivalent to the distance between the textField and the top of the keyboard and have it positioned so the bottom edge of the rect is right above the top of the textField being edited then try to scroll to it. I've checked the location and height of the rect which is correct, and I make sure it's not in the view but the scrollView doesn't scroll to it at all. My layout is like this, UIViewController > ScrollView with all edges tied to its superview edges set to 0 > UIView with its leading, trailing, bottom edges tied to its superiew set to 0 and top constraint of 35 to the ScrollView. I'd really like to stick to this approach if it's reasonable.
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillChange(notification: )),
name: NSNotification.Name.UIKeyboardDidShow, object:nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide(notification: )),
name: NSNotification.Name.UIKeyboardWillHide, object:nil)
}
@objc func keyboardWillChange(notification: NSNotification) {
// activeFrame is the frame of the textField in the window which is being edited
if let kb = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
self.view.frame.origin.y = -kb.height // moves the origin of the view up
// get the distance between the field being edited (activeFrame) and the top of the keyboard
let distance: CGFloat = abs((activeFrame?.frame.origin.y)! + (activeFrame?.frame.size.height)! - kbSize.height)
let yCord = (activeTextField?.frame.origin.y)! - distance
let rect = UIView(frame: CGRect(x: 0, y: yCord, width: 100, height: distance))
self.scrollView.scrollRectToVisible((rect.frame), animated: true)
}
}