I have a method on a view controller which scrolls text fields up when focused if the keyboard is on screen.
I have tried to do the same thing on a different controller but with a textview but it's not working.
Attempt:
func keyboardOnScreen(notification: NSNotification){
// Retrieve the size and top margin (inset is the fancy word used by Apple)
// of the keyboard displayed.
let info: NSDictionary = notification.userInfo!
let kbSize = info.valueForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue.size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize!.height, 0.0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
var aRect: CGRect = self.view.frame
aRect.size.height -= kbSize!.height
//you may not need to scroll, see if the active field is already visible
print("are we in here?")
if activeField != nil {
print("active field was not nil")
if (CGRectContainsPoint(aRect, activeField!.frame.origin) == false) {
let scrollPoint:CGPoint = CGPointMake(0.0, activeField!.frame.origin.y - kbSize!.height)
scrollView.setContentOffset(scrollPoint, animated: true)
}
}
}
func keyboardOffScreen(notification: NSNotification){
print("keyboard off screen")
let contentInsets:UIEdgeInsets = UIEdgeInsetsZero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
self.scrollView.setContentOffset(CGPointMake(0, -self.view.frame.origin.y/2), animated: true)
}
My controller extends the text view delegate. Active field is declared as an optional. And it is set in the following:
func textViewDidBeginEditing(textView: UITextView) {
activeField = textView
//other
}
func textViewDidEndEditing(commentTextView: UITextView) {
activeField = nil
//other
}