Как сделать автоматическую прокрутку стола вверх при показе клавиатуры? - PullRequest
0 голосов
/ 11 октября 2018

Первый вариант (работает) Если вы используете класс UITableViewController, прокрутка вверх работает автоматически.

Второй вариант (не работает) Но если вы используете UIViewController + UITableView, таблица автоматически не прокручивается вверх.

Скажите, пожалуйста, что я могу сделать для второго варианта?

Изменить размер tableView

func keyboardWillShow(_ notification: Notification) {
    //get the end position keyboard frame
    guard let keyInfo = notification.userInfo as NSDictionary? else {
        return
    }
    var keyboardFrame: CGRect = keyInfo.object(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! CGRect
    //CGRect keyboardFrame = [[keyInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    //convert it to the same view coords as the tableView it might be occluding
    keyboardFrame = self.tableView.convert(keyboardFrame, from: nil)
    //calculate if the rects intersect
    let intersect: CGRect = keyboardFrame.intersection(self.tableView.bounds)
    if (intersect != CGRect.null) {
        //yes they do - adjust the insets on tableview to handle it
        //first get the duration of the keyboard appearance animation
        let duration: TimeInterval = keyInfo.object(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! Double
        // adjust the animation curve - untested
        let curve: Int = (notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! Int) << 16
        //change the table insets to match - animated to the same duration of the keyboard appearance
        UIView.animate(withDuration: duration, delay: 0.2, options: UIView.AnimationOptions(rawValue: UInt(curve)), animations: {
            let height = intersect.size.height
            self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: height, right: 0)
            self.tableView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: height, right: 0)
        }, completion: nil)
    }
}
func keyboardWillHide(_ notification: Notification) {
    let keyInfo: NSDictionary = notification.userInfo! as NSDictionary
    let duration: TimeInterval = keyInfo.object(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! Double
    let curve: Int = (notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! Int) << 16
    //change the table insets to match - animated to the same duration of the keyboard appearance
    UIView.animate(withDuration: duration, delay: 0.2, options: UIView.AnimationOptions(rawValue: UInt(curve)), animations: {
        self.tableView.contentInset = UIEdgeInsets.zero
        self.tableView.scrollIndicatorInsets = UIEdgeInsets.zero
    }, completion: nil)
}

Как прокрутить до нужной ячейки?Как найти ячейку, в которой находится курсор?

Написал дополнительную функцию для ячейки

class CustomTableViewCell: UITableViewCell {
    func scrollToCell() {
        if let tableView = self.getTableView() {
            if let index = tableView.indexPath(for: self) {
                UIView.animate(withDuration: 0.2, animations: {
                    tableView.scrollToRow(at: index, at: .none, animated: false)
                }, completion: nil)
            }
        }
    }
    private func getTableView() -> UITableView? {
        return (self.superview as? UITableView)
    }
}

Я вызываю эту функцию при событиях:

UITextView::textViewDidBeginEditing
UITextField::textFieldDidBeginEditing

Я думаю, что есть лучший способ

1 Ответ

0 голосов
/ 11 октября 2018

Вы можете наблюдать, когда показывает клавиатура, а затем прокручивать таблицу вверх, как это:

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector:
            #selector(keyboardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
    }

    @objc
    func keyboardWillShow(_ notification: Notification) {
        let indexPath = IndexPath(row: 0, section: 0)
        self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...