UIKeyboardDidShowNotification called multiple times, and sometimes with incorrect keyboard dimensions

前端 未结 4 764
醉话见心
醉话见心 2021-02-07 08:12

I am trying to move a UITextView above the keyboard whenever the keyboard appears/changes. Let\'s say I have the English keyboard displaying and then switch directly to the Chin

4条回答
  •  清歌不尽
    2021-02-07 08:54

    In my case, I register for my keyboard notifications in ViewWillAppear and unregister in ViewWillDisappear too. But, It will cause the UIKeyboardDidShowNotification handler be fired multiple times. Seem like the unregister method do not work, so, every time the view appears, the counts of Observer for UIKeyboardDidShowNotification plus 1. Then, you touch inside UITextField, multiple Observer be notified, handler be fired again and again.

    So, you must register for keyboard notifications in ViewDidLoad and don't unregister. Just like the Apple mentioned in this page,

    // Call this method somewhere in your view controller setup code.

    I think the 'setup' means ViewDidLoad.And In the Handling the keyboard notifications code list,no ViewWillDisappear.

    Here's my handler for keyboard notify, and it work.

       func keyboardWillShow(notification: NSNotification) {
        let userInfo = notification.userInfo!
        let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().height
        debugPrint("Before",NotifyView.frame)
        NotifyView.frame.offsetInPlace(dx: 0, dy: -keyboardHeight)
        debugPrint("After",NotifyView.frame)
    }
    func keyboardWillHide(notification: NSNotification) {//Do Nothing
    }
    

提交回复
热议问题