NSNotificationCenter Swift 3.0 on keyboard show and hide

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

    KeyBoard Will Show And Hide With TxtField In 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)
    }
    

    }

提交回复
热议问题