NSNotificationCenter Swift 3.0 на клавиатуре показать и скрыть

Я пытаюсь запустить функцию, когда клавиатура показывает и исчезает и имеет следующий код:

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(ViewController.keyBoardUp(Notification :)), name:  NSNotification.Name.UIKeyboardWillShow, object: nil)

И функция keyBoardUp ниже:

func keyBoardUp( Notification: NSNotification){
    print("HELLO")
}

Однако функция не печатает на консоли при отображении клавиатуры. Помощь будет принята с благодарностью

Ответ 1

Свифт 3:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: Notification.Name.UIKeyboardWillHide, object: nil)

}

func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        print("notification: Keyboard will show")
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

Swift 4.2.1:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

@objc fileprivate func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        // Do something with size
    }
}

@objc fileprivate func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        // Do something with size
    }
}

Swift 4. 2+

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

}

@objc func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

@objc func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

Ответ 2

Свифт 4. 2+

Ответ @vandana обновлен, чтобы отразить изменения в родных уведомлениях в Swift 4.2.

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

}

@objc func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        print("notification: Keyboard will show")
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

@objc func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

Кроме того, вам нужно использовать UIKeyboardFrameEndUserInfoKey для учета изменений safeAreaInset представленных в iOS 11.

Ответ 3

установить наблюдателя уведомлений клавиатуры в

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}

и в вашей функции обрабатывать его

func keyboardNotification(notification: NSNotification) {
  print("keyboard displayed!!")
}

надеюсь, что это поможет вам.

Ответ 4

Swift 4.X/5

Мне нравится встроенный блочный подход, который доступен уже давно! Вы можете прочитать больше о параметрах addObserver(...) здесь.

Некоторые преимущества этого подхода:

  • вам не нужно использовать ключевое слово @objc
  • вы пишете код обратного вызова в том же месте, где вы настраиваете наблюдателя

Важное замечание: вызовите NotificationCenter.default.removeObserver(observer) в deinit объекта, для которого вы устанавливаете, зарегистрируйте наблюдателя (часто это контроллер представления).

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.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in

    // restore the layout of your UI before the keyboard has been shown
}

Ответ 5

Обновлено для быстрого:

// MARK:- Kyeboard hide/show methods

func keyboardWasShown(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }
}

func keyboardWillBeHidden(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == mEnterPasswordTextField || textField == mEnterConfirmPassword  {
            animateViewMoving(up: true, moveValue: 120)
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField == mEnterPasswordTextField || textField == mEnterConfirmPassword  {
            animateViewMoving(up: false, moveValue: 120)
    }
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
    let movementDuration:TimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration )
    self.view.frame = self.view.frame.offsetBy(dx: 0,  dy: movement)
    UIView.commitAnimations()
}

//В viewDidLoad()

self.registerForKeyboardNotifications()
self.deregisterFromKeyboardNotifications()

Ответ 6

Попробуй это

 override func viewDidLoad()
    {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

 @objc func keyboardWillShow(notification: NSNotification) {
      if(messageCount > 0)
      {
        tableView.scrollToRow(at: IndexPath(item:messageCount - 1, section: 0), at: .bottom, animated: true)
      }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if(messageCount > 0)
    {
        tableView.scrollToRow(at: IndexPath(item:0, section: 0), at: .top, animated: true)
    }
}

Ответ 7

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
    }
}

Ответ 8

Swift 4.2

Эта версия работает как на iPhone 5, так и на iPhone X. Она работает очень хорошо, если вы соблюдаете безопасную зону при настройках ограничений.

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

@objc func keyboardWillShow(notification: NSNotification) {
        if let _ = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.view.frame.origin.y = self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.size.height
            if self.emailTextField.isFirstResponder {
                self.view.frame.origin.y -= 100
            } else if self.passwordTextField.isFirstResponder {
                self.view.frame.origin.y -= 150
            } else if self.passwordConfirmTextField.isFirstResponder {
                self.view.frame.origin.y -= 200
            }
        }
}

@objc func keyboardWillHide(notification: NSNotification) {
        if self.view.frame.origin.y != 0 {
           self.view.frame.origin.y = self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.size.height
        }
}

Ответ 9

KeyBoard будет показывать и скрывать с TxtField в Swift 4

class ViewController: UIViewController {


@IBOutlet weak var commentsTxt: UITextField!
@IBOutlet weak var keyboardBottom: NSLayoutConstraint!

override func viewWillAppear(_ animated: Bool) {
    IQKeyboardManager.shared.enable = false
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(keyboardWillShow),
        name: UIResponder.keyboardWillShowNotification,
        object: nil
    )
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(keyboarddidHide),
        name: UIResponder.keyboardWillHideNotification,
        object: nil
    )
}

@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        self.keyboardBottom.constant = keyboardHeight - self.bottomLayoutGuide.length
        DispatchQueue.main.asyncAfter(deadline: .now()+0.1, execute: {
            let bottomOffset = CGPoint(x: 0, y: self.scrlView.contentSize.height - self.scrlView.bounds.size.height)
            self.scrlView.setContentOffset(bottomOffset, animated: true)
        })
    }
}
@objc func keyboarddidHide(_ notification: Notification) {
    self.keyboardBottom.constant = 0

}

   override func viewWillDisappear(_ animated: Bool) {
    IQKeyboardManager.shared.enable = true
     NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}

}