键盘上的NSNotificationCenter Swift 3.0显示和隐藏

问题描述 投票:12回答:8

我试图在键盘显示和消失时运行一个函数,并具有以下代码:

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

但是,当键盘显示时,该功能不会打印到控制台。非常感谢帮助

ios swift keyboard-events nsnotificationcenter
8个回答
27
投票

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

23
投票

Swift 4.2+

@vandana's答案已更新,以反映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来解释iOS 11引入的safeAreaInset更改。


5
投票

设置键盘通知观察器

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!!")
}

希望这会帮助你。


1
投票

更新为swift:

// 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()

1
投票

试试这个

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

1
投票

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

1
投票

Swift 4.X / 5

我喜欢内联,基于块的方法,已经有很长一段时间了!您可以阅读更多关于addObserver(...) here的参数。

这种方法的一些优点是:

  • 您不需要使用@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
}

0
投票

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
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.