首页 > 解决方案 > tableView重新加载时如何解决键盘问题?

问题描述

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

ps:每次都要调用API。

动图


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

标签: iosswiftuitableviewscrollkeyboard

解决方案


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


推荐阅读