How to write Keyboard notifications in Swift 3

前端 未结 10 1566
清歌不尽
清歌不尽 2020-12-08 10:37

I\'m trying to update this code to swift 3:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(\"keyboardWillShow:\"), name: UIKeyboar         


        
10条回答
  •  独厮守ぢ
    2020-12-08 11:18

    Here is the best solution that works for me as far (used from "Lets Build That App" YouTube channel)

    class ChatVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
    
    // reference to your UIView with message TextField
    
        @IBOutlet weak var ChatView: UIView!   
    
    
    // bottom constrain to your UIView (in my case ChatView)
    
        var bottomConstraint: NSLayoutConstraint?  
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
    // add some text in the placeholder if you want
    
            messageField.placeholder = "Type your message.." 
    
    // here we add two notifications for showing and hiding the keyboard
    
            NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
    
            NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
    
    
    // defines the start position for message textField that will be shown on the screen
    
            bottomConstraint = NSLayoutConstraint(item: ChatViewField!, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: -40)    
            view.addConstraint(bottomConstraint!)    
        }
    
    // handles notifications for both cases when keyboard pops up and disappears  
    
      @objc func handleKeyboardNotification(notification: NSNotification){
            if let userInfo = notification.userInfo {
    
                let keyboardFrame =  (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
                print(keyboardFrame)
    
                let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
    
                bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame.height : -40
    
    // makes animation at the same time as the keyboard
    
    UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
    
                    self.view.layoutIfNeeded()
                }) { (completed) in    
                }   
            }
        }
    

提交回复
热议问题