NSNotificationCenter Swift 3.0 on keyboard show and hide

后端 未结 9 2210
日久生厌
日久生厌 2020-12-05 19:49

I am trying to run a function when the keyboard shows and disappears and have the following code:

let notificationCenter = NotificationCenter.default
notific         


        
9条回答
  •  旧巷少年郎
    2020-12-05 20:15

    Swift 4.2

    NotificationCenter.default.addObserver(self, selector: #selector(didReceiveKeyboardNotificationObserver(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(didReceiveKeyboardNotificationObserver(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    
    @objc func didReceiveKeyboardNotificationObserver(_ notification: Notification) {
        let userInfo = notification.userInfo
        let keyboardBounds = (userInfo!["UIKeyboardBoundsUserInfoKey"] as! NSValue).cgRectValue
        let keyboardFrame = (userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        let duration = userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        let curve = userInfo!["UIKeyboardAnimationCurveUserInfoKey"] as! Int
        let frameBegin = (userInfo!["UIKeyboardFrameBeginUserInfoKey"] as! NSValue).cgRectValue
        let centerBegin = (userInfo!["UIKeyboardCenterBeginUserInfoKey"] as! NSValue).cgPointValue
        let center = (userInfo!["UIKeyboardCenterEndUserInfoKey"] as! NSValue).cgPointValue
        let location = userInfo!["UIKeyboardIsLocalUserInfoKey"] as! Int
        println("keyboardBounds: \(keyboardBounds) \nkeyboardFrame: \(keyboardFrame) \nduration: \(duration) \ncurve: \(curve) \nframeBegin:\(frameBegin) \ncenterBegin:\(centerBegin)\ncenter:\(center)\nlocation:\(location)")
        switch notification.name {
        case UIResponder.keyboardWillShowNotification:
        // keyboardWillShowNotification
        case UIResponder.keyboardWillHideNotification:
        // keyboardWillHideNotification
        default:
            break
        }
    }
    

提交回复
热议问题