显示和隐藏键盘时,UITableView节的页脚问题

时间:2019-04-11 12:15:17

标签: ios uitableview uitextfield uitableviewsectionheader

我有一个UITableView,其中包含节的页眉和页脚。在一个单元格中,我有一个UITextField,它触发键盘的显示。

出现键盘时,仅有时(它在某种程度上取决于表格的滚动位置)最后一个部分的页脚会正确向上移动,因此此页脚会出现在keyboard上方。

但是当我再次隐藏键盘时,页脚将停留在该位置,直到通过进一步的用户交互刷新表格为止。如何避免这种情况或至少以编程方式强制执行刷新?

tableView.reloadData()无济于事。

请注意,它仅在iPhone上发生,而不在iPad上发生。到目前为止,仅使用iOS 12.2进行了测试。

1 个答案:

答案 0 :(得分:0)

override func viewWillAppear(_ animated: Bool) {
    self.registerForKeyboardNotifications()
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
    self.deregisterFromKeyboardNotifications()
    super.viewWillDisappear(animated)
}



func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name:
        UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}


@objc func keyboardWasShown(notification: NSNotification){

    //Need to calculate keyboard exact size due to Apple suggestions
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
    //let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.size.height, right: 0.0)
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    //var info = notification.userInfo!
    //let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    //let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)

     tableview.transform = CGAffineTransformMakeScale(1, -1);

}