MarcoCabazal
5/6/2015 - 8:39 AM

Scroll UITextField above Keyboard in a UITableView OR UIScrollView in Swift

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;
    }