簡體   English   中英

鍵盤上的 NSNotificationCenter Swift 3.0 顯示和隱藏

[英]NSNotificationCenter Swift 3.0 on keyboard show and hide

我試圖在鍵盤顯示和消失時運行一個函數,並具有以下代碼:

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

但是,當鍵盤顯示時,該函數不會打印到控制台。 幫助將不勝感激

斯威夫特 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
        }
    }
}

斯威夫特 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
    }
}

斯威夫特 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
        }
    }
}

斯威夫特 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來說明iOS 11引入的safeAreaInset更改。

設置鍵盤通知觀察者

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.X / 5

我喜歡內聯的、基於塊的方法,它已經存在很長時間了! 您可以在此處閱讀有關addObserver(...)參數的更多信息。

這種方法的一些優點是:

  • 你不需要使用@objc 關鍵字
  • 您在設置觀察者的同一位置編寫回調代碼

重要提示:在您設置注冊觀察者(通常是視圖控制器)的對象的deinit中調用NotificationCenter.default.removeObserver(observer) )。

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
}

快速更新:

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

// 在 vi​​ewDidLoad()

self.registerForKeyboardNotifications()
self.deregisterFromKeyboardNotifications()

鍵盤將在 Swift 4 中使用 TxtField 顯示和隱藏

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

}

嘗試這個

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

斯威夫特 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
    }
}

斯威夫特 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
        }
}

斯威夫特 > 4.++

您可以使用協議和協議擴展。 讓我們創建 KeyboardListener 協議

protocol KeyboardListener: class {
   func registerKeyboardObserver()
   func keyboardDidUpdate(keyboardHeight: CGFloat)
   func removeObserver()
}

然后在 UIViewController 擴展中創建@objc 函數

extension UIViewController {
@objc func adjustForKeyboard(notification: Notification) {
    guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
    
    let keyboardScreenEndFrame = keyboardValue.cgRectValue
    let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
    
    if notification.name == UIResponder.keyboardWillHideNotification {
        if let keyboardLister = self as? KeyboardListener {
            keyboardLister.keyboardDidUpdate(keyboardHeight: .zero)
        }
    } else {
        if let keyboardLister = self as? KeyboardListener {
            keyboardLister.keyboardDidUpdate(keyboardHeight: keyboardViewEndFrame.height - view.safeAreaInsets.bottom)
        }
    }
}

}

然后,將鍵盤偵聽器擴展用於默認實現

extension KeyboardListener where Self: UIViewController {
func registerKeyboardObserver() {
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
    notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}

func removeObserver() {
    NotificationCenter.default.removeObserver(self)
}

}

最后,我們可以從我們的 ViewController 類中使用它

extension EditProfileVC: KeyboardListener {
func keyboardDidUpdate(keyboardHeight: CGFloat) {
    //update view when keyboard appear, 
}

}

並從 viewwillAppear 調用 register 並從 deinit 調用 removeObserver

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    registerKeyboardObserver()
}

deinit {
   removeObserver()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM