代码之家  ›  专栏  ›  技术社区  ›  Dani iman kazemayni

在键盘上方显示UIView无法正常工作

  •  1
  • Dani iman kazemayni  · 技术社区  · 6 年前

    我在试着移动 constraintToBottom.constant UIView 我的朋友呢 UITextField 显示后位于键盘上方。我设置了 Notification 观察者,但由于某种原因它不起作用。

    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: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            UIView.animate(withDuration: 0.3, animations: {
                self.constraintToBottom.constant = keyboardSize.height
                print("constant", self.constraintToBottom.constant)
            })
        }
    }
    

    当我打印

    常数346.0

    然而,这个 UIView视图

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Shehata Gamal    6 年前

    您需要重新布局视图

    self.constraintToBottom.constant = -1 * keyboardSize.height
    UIView.animate(withDuration: 0.3, animations: {
         self.view.layoutIfNeeded()
         print("constant", self.constraintToBottom.constant)
    })