Move UIView up when the keyboard appears in iOS

后端 未结 18 1810
再見小時候
再見小時候 2020-11-28 20:38

I have a UIView, it is not inside UIScrollView. I would like to move up my View when the keyboard appears. Before I tried to use this solution: How can I make a UITextField

18条回答
  •  情深已故
    2020-11-28 20:52

    Based on theDunc's answer but written in Swift with Autolayout.

    @IBOutlet weak var bottomConstraint: NSLayoutConstraint! // connect the bottom of the view you want to move to the bottom layout guide
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(ConversationViewController.keyboardWillShow(_:)),
                                                         name: UIKeyboardWillShowNotification,
                                                         object: nil)
    
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(ConversationViewController.keyboardWillHide(_:)),
                                                         name: UIKeyboardWillHideNotification,
                                                         object: nil)
    }
    
    override func viewWillDisappear(animated: Bool) {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
        super.viewWillDisappear(animated)
    }
    
    // MARK: - Keyboard events
    
    func keyboardWillShow(notification: NSNotification) {
        if let userInfo = notification.userInfo,
            keyboardFrame = userInfo[UIKeyboardFrameBeginUserInfoKey]
        {
            let keyboardSize = keyboardFrame.CGRectValue().size
            self.bottomConstraint.constant = keyboardSize.height
            UIView.animateWithDuration(0.3) {
                self.view.layoutIfNeeded()
            }
        }
    }
    
    func keyboardWillHide(notification: NSNotification) {
        self.bottomConstraint.constant = 0
        UIView.animateWithDuration(0.3) {
            self.view.layoutIfNeeded()
        }
    }
    

提交回复
热议问题