Below is the code that I'm trying to use to have the view scroll only when the focused textField or UIButton is hidden by the keyboard:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var buttonToBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var textFieldUsername: UITextField!
@IBOutlet weak var textFieldPassword: UITextField!
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillBeShown:", name: UIKeyboardWillShowNotification, object: nil)
}
func textFieldDidBeginEditing(textField: UITextField) {
}
func textFieldShouldReturn(textField: UITextField) -> Bool {textField.resignFirstResponder()
return true
}
func keyboardWillBeHidden(notification: NSNotification){
self.scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
}
func keyboardWillBeShown(notification: NSNotification){
let userInfo = notification.userInfo!
if let kbsize = userInfo[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue().size{
self.scrollView .setContentOffset(CGPointMake(0, kbsize.or), animated: true)
}
}
}
Problem: The View scrolls even when the keyboard is not hiding anything.
View at Launch:
View Upon Tapping on a TextField:
Question: How do I check to see if the focused field is hidden by the keyboard, and ONLY if it is, push it above it?
Project: TextFieldScroll
EDIT
App works fine in Portrait mode, however, not in landscape mode. Also in landscape mode, when the Username textField keyboard is up and I tap the Password textField, it remains hidden behind the keyboard. I updated the project on Github and fixed the link. Thanks
Screen shot in landscape: