当键盘弹出时改变约束 - Swift

5

我有一个UIView,当键盘出现时它无法正确移动。在UIView中有一个UITextView,我用它来输入文本。如果我选择TextView输入文本,键盘会出现,但是第一次UIView不会移动。如果我点击背景使键盘消失,然后再次点击TextView,那么UIView就会正确地上移。有人知道这里发生了什么吗?

class ChatViewController: UIViewController, CNContactPickerDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, UIToolbarDelegate, UITextFieldDelegate, UITextViewDelegate {

@IBOutlet weak var composeTextView: UITextView!

@IBOutlet weak var composeViewBottomConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()

    composeTextView.delegate = self

}

func textViewDidBeginEditing(_ textView: UITextView) {

    UIView.animate(withDuration: 0.5){
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

    }

    self.view.layoutIfNeeded()


}

@objc func keyboardWillShow(notification: Notification) {
    let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue

    let keyboardHeight = keyboardSize?.height

        if #available(iOS 11.0, *){

            self.composeViewBottomConstraint.constant = keyboardHeight! - view.safeAreaInsets.bottom
        }
        else {
            self.composeViewBottomConstraint.constant = view.safeAreaInsets.bottom
        }
        self.view.layoutIfNeeded()

}

}

嗨,badman!你想要的是在键盘出现时将 UIView 向上移动,在键盘消失时将其向下移动,对吧? - Lenin
是的,没错 Lenin。 - badman
请查看我的答案:https://dev59.com/P1wZ5IYBdhLWcg3wJ9nN#60643471 - Muhammad Asyraf
1个回答

25
问题在于textView的第一次点击无法将视图上移,因为showKeyboard observer是在beginEditing中添加的,所以这一行代码应该放在viewDidLoad中。
  NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
  NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

除了以下修复之外

func textViewDidBeginEditing(_ textView: UITextView) {

     // I think no need for it

}

 @objc func keyboardWillShow(notification: Notification) {

     let keyboardSize = (notification.userInfo?  [UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue

     let keyboardHeight = keyboardSize?.height

     if #available(iOS 11.0, *){

          self.composeViewBottomConstraint.constant = keyboardHeight! - view.safeAreaInsets.bottom
      }
      else {
           self.composeViewBottomConstraint.constant = view.safeAreaInsets.bottom
         }

       UIView.animate(withDuration: 0.5){

          self.view.layoutIfNeeded()

       }


   }

  @objc func keyboardWillHide(notification: Notification){

      self.composeViewBottomConstraint.constant =  0 // or change according to your logic  

       UIView.animate(withDuration: 0.5){

          self.view.layoutIfNeeded()

       }

  }

1
你真是救星!这么简单的修复,我不知道怎么会错过它。谢谢。 - badman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接