Skip to content

Instantly share code, notes, and snippets.

@benjaminhorner
Last active May 31, 2022 12:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjaminhorner/1db43dfb6a314c6da515 to your computer and use it in GitHub Desktop.
Save benjaminhorner/1db43dfb6a314c6da515 to your computer and use it in GitHub Desktop.
Scroll UITextField above Keyboard in a UITableView OR UIScrollView in Swift
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
let contentInsets = UIEdgeInsets(top: self.tableView.contentInset.top, left: 0, bottom: keyboardSize.height, right: 0)
self.tableView.contentInset = contentInsets
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
var aRect: CGRect = self.view.frame
aRect.size.height -= keyboardSize.height
let activeTextFieldRect: CGRect?
let activeTextFieldOrigin: CGPoint?
if self.activeTextField != nil {
println("activeTextField not nil !")
activeTextFieldRect = self.activeTextField?.superview?.superview?.frame
activeTextFieldOrigin = activeTextFieldRect?.origin
self.tableView.scrollRectToVisible(activeTextFieldRect!, animated:true)
}
else if self.activeTextView != nil {
println("activeTextView not nil !")
activeTextFieldRect = self.activeTextView?.superview?.superview?.frame
activeTextFieldOrigin = activeTextFieldRect?.origin
self.tableView.scrollRectToVisible(activeTextFieldRect!, animated:true)
}
}
}
func keyboardWillHide(notification: NSNotification) {
let contentInsets = UIEdgeInsets(top: self.tableView.contentInset.top, left: 0, bottom: 0, right: 0)
self.tableView.contentInset = contentInsets
self.activeTextField = nil
self.activeTextView = nil
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
println("Should begin editing")
self.activeTextField = textField
return true;
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
println("Should begin editing")
self.activeTextView = textView
return true;
}
@yo113
Copy link

yo113 commented May 25, 2020

Worked

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment