клавиатураWillShowNotification вызывается дважды при отклонении - PullRequest
0 голосов
/ 11 июня 2018

Я подписался на keyboardWillShowNotification и keyboardWillHideNotification, чтобы перемещаться по моему интерфейсу.Я заметил, что когда я отклоняю клавиатуру, нажимая кнопку «Перейти», keyboardWillShowNotification вызывается дважды (таким образом, сбрасывая некоторые из моих ограничений), однако, если отклонить нажатием клавиши return на клавиатуре (MacBook), то она не вызывается дважды.

Как я могу избежать вызова дважды?Почему это поведение даже там?Я не могу найти упоминаний об этом (множество ссылок на него вызывается дважды с помощью входных представлений ... и т. Д.), Но никогда при отклонении.

Вот мой код:

override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasDismissed(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) 
}

и ...

@objc func keyboardNotification(notification: NSNotification) {
        guard
            let animationDuration = notification.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double,
            let animationCurve = notification.userInfo?["UIKeyboardAnimationCurveUserInfoKey"] as? NSNumber,
            let frameEnd = notification.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect,
            let frameBegin = notification.userInfo?["UIKeyboardFrameBeginUserInfoKey"]
            else {
                print("No userInfo recived from NSNotification.Name.UIKeyboardWillShow")
                return
        }
        print("WILL SHOW")

        let margin = self.view.safeAreaLayoutGuide
        constraintsWhenKeyboardVisible = [
                            boxOffice.leadingAnchor.constraint(equalTo: margin.leadingAnchor),
                            boxOffice.trailingAnchor.constraint(equalTo: margin.trailingAnchor),
                            boxOffice.bottomAnchor.constraint(equalTo: margin.bottomAnchor),
                            boxOffice.topAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -(frameEnd.height + 50))
                        ]
        NSLayoutConstraint.deactivate(boxOfficeFinalConstraints)
        NSLayoutConstraint.activate(constraintsWhenKeyboardVisible)

        UIView.animate(withDuration: animationDuration,
                       delay: TimeInterval(0),
                       options: UIView.AnimationOptions(rawValue: animationCurve.uintValue),
                       animations: {
                        self.boxOffice.answerField.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
                        self.view.layoutIfNeeded()
        },
                       completion: nil)
    }


@objc func keyboardWasDismissed(notification: NSNotification) {
        guard
            let animationDuration = notification.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double,
            let animationCurve = notification.userInfo?["UIKeyboardAnimationCurveUserInfoKey"] as? NSNumber
            else {
                print("No userInfo recived from NSNotification.Name.UIKeyboardWillShow")
                return
        }
        print("WILL HIDE")
        //print(notification)
        NSLayoutConstraint.deactivate(self.constraintsWhenKeyboardVisible)
        NSLayoutConstraint.activate(self.boxOfficeFinalConstraints)

        UIView.animate(withDuration: animationDuration,
                       delay: TimeInterval(0),
                       options: UIView.AnimationOptions(rawValue: animationCurve.uintValue),
                       animations: {
                        self.boxOffice.answerField.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
                        self.view.layoutIfNeeded()
        },
                       completion: nil)

    }

1 Ответ

0 голосов
/ 12 июня 2018

Я не решил проблему публикации клавиатурыWillShowNotification, когда Return нажата на симуляторе клавиатуры iOS, но не на аппаратной клавиатуре симулятора, но я изменил свой код так, чтобы при отображении клавиатуры я недобавить ограничения, я просто изменяю константу ограничения, используя высоту из уведомления клавиатуры.Это решило это.

boxOfficeWhenKeyboardVisible[3].constant = -(frameEnd.height + 50)
...