Scroll UITextField above Keyboard in a UITableViewCell on a regular UIViewController

前端 未结 10 1139
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 14:17

I have tried most of the examples here on StackOverflow. I also used Apple\'s. The problem I seem to have with them is that they don\'t account for the UITextField being in

10条回答
  •  误落风尘
    2020-11-27 14:31

    I made a mix with the answers of Matt and also Salman. This works for many textfields in a tableView. Swift 3

    Basically is get the BOTTOM Y point of the textInput touched. Once we have that I check if the keyboard cover the textInput and if do it I would change the contentOffset of the tableView

    First register to the notifications. In the init if is a UIView or in viewDidLoad if is a UIViewController:

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    

    Then set up the textfield touched as current input

    var inputActive: UITextField!
    
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        inputActive = textInput
        return true
    }
    

    Finally implement the notifications method:

    func keyboardWillShow(notification: NSNotification) {
        var userInfo = notification.userInfo!
        if let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            // Get my height size
            let myheight = tableView.frame.height
            // Get the top Y point where the keyboard will finish on the view
            let keyboardEndPoint = myheight - keyboardFrame.height
            // Get the the bottom Y point of the textInput and transform it to the currentView coordinates.
            if let pointInTable = inputActive.superview?.convert(inputActive.frame.origin, to: tableView) {
                let textFieldBottomPoint = pointInTable.y + inputActive.frame.size.height + 20
                // Finally check if the keyboard will cover the textInput
                if keyboardEndPoint <= textFieldBottomPoint {
                    tableView.contentOffset.y = textFieldBottomPoint - keyboardEndPoint
                } else {
                    tableView.contentOffset.y = 0
                }
            }
        }
    }
    
    func keyboardWillHide(notification: NSNotification) {
        tableView.contentOffset.y = 0
    }
    

    Few things to add. The padding is some extra distance that I add in my case was 20 points. Also in my case the UITableView was added to a UIViewController but this should work also in a UITableViewController

    Hope this helps!

提交回复
热议问题