NSNotificationCenter Swift 3.0 on keyboard show and hide

后端 未结 9 2237
日久生厌
日久生厌 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:01

    Swift 4.X / 5

    I like the inline, block-based approach which is available for a long time already! You can read more about the parameters of addObserver(...) here.

    Some advantages of this approach are:

    • you don't need to use the @objc keyword
    • you write your callback code at the same location where you setup your observer

    Important: Call NotificationCenter.default.removeObserver(observer) in the deinit of the object where you set register the observer (often a view controller).

    let center = NotificationCenter.default
    
    let keyboardWillShowObserver: NSObjectProtocol = center.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
        guard let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
        let height = value.cgRectValue.height
    
        // use the height of the keyboard to layout your UI so the prt currently in
        // foxus remains visible
    }
    
    let keyboardWillHideObserver: NSObjectProtocol = center.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { (notification) in
    
        // restore the layout of your UI before the keyboard has been shown
    }
    

提交回复
热议问题