Scroll UITextField above Keyboard in a UITableViewCell on a regular UIViewController

前端 未结 10 1132
被撕碎了的回忆
被撕碎了的回忆 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:27

    jqgsninimo's solution updated to 4.2. Works on iOS 12.0.

    Swift 4.2

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(with:)), name: UIResponder.keyboardDidShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(with:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc func keyboardDidShow(with notification: Notification) {
        guard let userInfo = notification.userInfo as? [String: AnyObject],
            let keyboardFrame = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
            else { return }
    
        var contentInset = self.tableView.contentInset
        contentInset.bottom += keyboardFrame.height
    
        tableView.contentInset = contentInset
        tableView.scrollIndicatorInsets = contentInset
    }
    
    @objc func keyboardWillHide(with notification: Notification) {
        guard let userInfo = notification.userInfo as? [String: AnyObject],
            let keyboardFrame = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
            else { return }
    
        var contentInset = self.tableView.contentInset
        contentInset.bottom -= keyboardFrame.height
    
        tableView.contentInset = contentInset
        tableView.scrollIndicatorInsets = contentInset
    }
    

提交回复
热议问题