swift UITableView прокручивается вверх, когда появляется клавиатура, но я не вижу верхние ячейки - PullRequest
0 голосов
/ 28 января 2020

У меня есть ViewController с TableView и textView. Я использую следующий код, так что когда клавиатура появляется, она поднимает textView и Tableview вверх.

bindToKeyboard

extension UIView {

    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector:
            #selector(UIView.keyboardWillChange(_:)), name:
            UIResponder.keyboardWillChangeFrameNotification, object: nil)
    }

    @objc func keyboardWillChange(_ notification: NSNotification) {
        let duration = notification.userInfo!
        [UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey]
            as! UInt
        let curFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey]
            as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey]
            as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options:
            UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
                self.frame.origin.y += deltaY

        },completion: {(true) in
            self.layoutIfNeeded()
        })
    }
}

У меня проблема с верхними ячейками в tableView, я не могу прокрутить вниз, чтобы отобразить их, пока я не закрою клавиатура. Я искал возможные примеры кода, чтобы исправить это, но я не могу найти правильное решение. Любой вклад с благодарностью.

keyboard is hiden

keyboard is shown

РЕШЕНИЕ

Добавлено наблюдатель для viewDidLoad

let notificationCenter = NotificationCenter.default

notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)

notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)

это было добавлено к классу

 @objc func adjustForKeyboard(notification: Notification) {

        guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }

        let keyboardScreenEndFrame = keyboardValue.cgRectValue

        let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)

        if notification.name == UIResponder.keyboardWillHideNotification {
            tableView.contentInset = .zero
        } else {
            //Modify the top insets to 350 and the height of the keyboard > 10 ? 10 : 10
            //to eliminate the gap between the bottom cell and the textView
            tableView.contentInset = UIEdgeInsets(top: 350, left: 0, bottom: keyboardViewEndFrame
                .height > 10 ? 10 : 10, right: 0)
        }
        tableView.scrollIndicatorInsets = tableView.contentInset
    }

надеюсь, это кому-нибудь поможет.

Ответы [ 2 ]

1 голос
/ 28 января 2020

Вы изменяете frame представления таблицы, но вам следует изменить свойство contentOffset или contentInsets.

Если вы переместите кадр, вся таблица сместится за пределы экрана, следовательно, верхние ячейки также находятся вне экрана.

Существует множество (и со многими, я имею в виду, много ) учебных пособий, которые могут вам помочь, см., например, https://www.hackingwithswift.com/example-code/uikit/how-to-adjust-a-uiscrollview-to-fit-the-keyboard

Также на github можно найти несколько решений.

0 голосов
/ 28 января 2020

вы также можете использовать IQKeyboardManager cocoapod в вашем проекте

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...