简体   繁体   中英

swift screen move when keyboard appears

I have a textview and a text field on my screen and I want move screen when edit textview. This is my code

    override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)

 //   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)

    print("addd observer")

}
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
 //   NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}

@objc func keyboardWillShow(_ sender: Notification) {
    let keyboardSize = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
    print("keyboardwillshow")
    ksize = keyboardSize?.height

}


@objc func textViewDidBeginEditing(_ textView: UITextView) {
        print("textviewedit")
        boxview.frame.origin.y -= ksize
        print("textview")



}
@objc func textViewDidEndEditing(_ textView: UITextView) {

    print("textvieweditend")
    boxview.frame.origin.y = 0

}

It works when I just edit textview. However, if I edit the textview right after focus on the textfield(without exit keyboard) it doens't work. I already checked that textviewDidBeginEditing() is called but the screen doesn't move.. How can I solve this? All advises are welcome!

I add self.view.Layoutifneeded() to keyboardwillchange() and it works!! thanks everybody.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM