Перемещение UIView, чтобы избежать наложения на клавиатуру - PullRequest
0 голосов
/ 01 октября 2018

У меня есть пользовательский UIViewController, в котором я реализовал пользовательский диалог ввода пользователя.Когда пользователь нажимает на UITextField, появляется клавиатура и окно сообщений перемещается вверх.

Код работает нормально в первый раз.Однако, когда я закрываю контроллер представления, содержащий диалоговое окно с настраиваемым сообщением, и снова выполняю его, UIView, реализующий диалоговое окно пользовательского ввода, похоже, не движется должным образом (пропуская введенное мной смещение)

СначалаЯ реализовал расширение для UIViewController (используя примеры кода из этого поста и этого поста )

extension UIViewController {

    // forHeight is the height of the message view that will be shifted up/down
    func setNotificationCentreForKeyboardEvents(forHeight:CGFloat) {
        // Set the selector functions for NSNotification.Name.UIKeyboardWillShow/Hide
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: Notification.Name.UIKeyboardWillHide, object: nil)
    }

    // In order for this function to work, the "tag" the message view that is goingto be moved up
    // needs to be set to 55
    @objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue,
            let messageView = self.view.viewWithTag(55) {

            // create a rect with the dimensions of the keyboard
            let aRectY:CGFloat = self.view.frame.height - keyboardSize.height
            let aRect = CGRect(x: 0, y: aRectY, width: self.view.frame.size.width, height: keyboardSize.height)

            // find the inersection of this rect with the message view
            let intersection = aRect.intersection(messageView.frame)

            if self.view.frame.origin.y == 0 {
                self.view.frame.origin.y -= intersection.size.height+20
            }
        }
    }

    // In order for this function to work, the "tag" the message view that is goingto be moved down
    // needs to be set to 55
    @objc func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue,
            let messageView = self.view.viewWithTag(55) {

            // create a rect with the dimensions of the keyboard
            let aRectY:CGFloat = self.view.frame.height - keyboardSize.height
            let aRect = CGRect(x: 0, y: aRectY, width: self.view.frame.size.width, height: keyboardSize.height)

            // find the inersection of this rect with the message view
            let intersection = aRect.intersection(messageView.frame)

            if self.view.frame.origin.y == 0 {
                self.view.frame.origin.y += intersection.size.height - 20
            }
        }
    }
}

В моем собственном UIViewController, содержащем диалог ввода пользователя, У меня есть

override func viewDidLoad() {
...

    messageView.tag = 55
    setNotificationCentreForKeyboardEvents(forHeight: messageView.frame.size.height)
...
}

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

    NotificationCenter.default.removeObserver(self)
}

, и viewController, выполняющий переход к представлению, содержащему пользовательский диалог ввода, имеет

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == showItemSegueName) {
        let destination = segue.destination as! ItemsViewController
        destination.listName = selectedListName
    } else if (segue.identifier == "addListSegue") {
        let newController: AddListingDialogViewController = segue.destination as! AddListingDialogViewController
        newController.modalPresentationStyle = .overFullScreen
    }
}

Вот как он ведет себя

enter image description here

Что мне здесь не хватает?Почему код не работает должным образом после первого запуска перехода?

Спасибо

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