tableView重新加载时如何解决键盘问题?

问题描述

我在键盘和 tableview 之间有问题。单击单元格时,API 调用获取新数据。同时,当单击单元格键盘打开并且 tableview.reloadData() 中出现滚动问题时。我正在调用单击单元格 -> api 调用获取新数据 -> tableView 重新加载 -> tableview 滚动到顶部和以后的键盘 Willshow 函数将单元格带到键盘的顶部(从顶部向下滚动到底部)。我该如何解决

P.s:每次我必须调用 API。

GifImage


fileprivate func addingNotifications() {
        //Subscribe to a Notification which will fire before the keyboard will show
        subscribetoNotification(UIResponder.keyboardWillShowNotification,selector: #selector(keyboardWillShowOrHide))

        //Subscribe to a Notification which will fire before the keyboard will hide
        subscribetoNotification(UIResponder.keyboardWillHideNotification,selector: #selector(keyboardWillShowOrHide))
    }

@objc func keyboardWillShowOrHide(notification: NSNotification) {
            // Get required info out of the notification
        if let scrollView = tableView,let userInfo = notification.userInfo,let endValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey],let durationValue = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey],let curveValue = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] {

            // Transform the keyboard's frame into our view's coordinate system
            let endRect = view.convert((endValue as AnyObject).cgRectValue,from: view.window)

            // Find out how much the keyboard overlaps our scroll view
            let keyboardOverlap = scrollView.frame.maxY - endRect.origin.y

            // Set the scroll view's content inset & scroll indicator to avoid the keyboard
            scrollView.contentInset.bottom = keyboardOverlap + 50
            scrollView.scrollIndicatorInsets.bottom = keyboardOverlap + 50

            let duration = (durationValue as AnyObject).doubleValue
            let options = UIView.Animationoptions(rawValue: UInt((curveValue as AnyObject).integerValue << 16))
            UIView.animate(withDuration: 0,delay: 0,options: options,animations: {
                self.view.layoutIfNeeded()
            },completion: nil)
        }
    }

解决方法

我不确定您在这里期望什么样的行为,但是如果您想退出/隐藏键盘,那么您可以在 tableview 中编写 self.view.endEditing() 将选择委托方法(告诉委托一行是即将被选中)