Last active
May 31, 2022 12:21
-
-
Save benjaminhorner/1db43dfb6a314c6da515 to your computer and use it in GitHub Desktop.
Scroll UITextField above Keyboard in a UITableView OR UIScrollView in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Worked