Scroll UITextField above Keyboard in a UITableViewCell on a regular UIViewController

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

    My solution (worked on Xcode 8.3.3, Swift 3, iOS 10.3.1):

    class MyTableViewController: UITableViewController {
    
        override func viewWillAppear(_ animated: Bool) {
            NotificationCenter.default.addObserver(self, selector: #selector(actionKeyboardDidShow(with:)), name: .UIKeyboardDidShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(actionKeyboardWillHide(with:)), name: .UIKeyboardWillHide, object: nil)
        }
    
        override func viewDidDisappear(_ animated: Bool) {
            NotificationCenter.default.removeObserver(self, name: .UIKeyboardDidShow, object: nil)
            NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
        }
    
        @objc private func actionKeyboardDidShow(with notification: Notification) {
            guard let userInfo = notification.userInfo as? [String: AnyObject],
                let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
                else { return }
    
            var contentInset = self.tableView.contentInset
            contentInset.bottom += keyboardFrame.height
    
            self.tableView.contentInset = contentInset
            self.tableView.scrollIndicatorInsets = contentInset
        }
    
        @objc private func actionKeyboardWillHide(with notification: Notification) {
            guard let userInfo = notification.userInfo as? [String: AnyObject],
                let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
                else { return }
    
            var contentInset = self.tableView.contentInset
            contentInset.bottom -= keyboardFrame.height
    
            self.tableView.contentInset = contentInset
            self.tableView.scrollIndicatorInsets = contentInset
        }
    
    }
    

提交回复
热议问题