简体   繁体   中英

Resize UITextView when keyboard appears

I try to resize the height of a UITextView-field when the keyboard appears (iOS 14.2, Xcode 12.3). The distance from the bottom of the UITextView to the save area is 90 and hence the lower part of it is hidden by the keyboard and can't be seen while editing.

I tried it with the solution shown here: Resize the UITextView when keyboard appears

Accordingly, my code is as follows:

class EditierenVC: UIViewController, UITextFieldDelegate, UITextViewDelegate {


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(false)
    NotificationCenter.default.addObserver(
               self,
               selector: #selector(EditierenVC.handleKeyboardDidShow(notification:)),
               name: UIResponder.keyboardDidShowNotification,
               object: nil
           )
    NotificationCenter.default.addObserver(
               self,
               selector: #selector(EditierenVC.handleKeyboardWillHide),
               name: UIResponder.keyboardWillHideNotification,
               object: nil
           )
}


@objc func handleKeyboardDidShow(notification: NSNotification) {
    guard let endframeKeyboard = notification
                .userInfo![UIResponder.keyboardFrameEndUserInfoKey]
                as? CGRect else { return }
    textfeld.contentInset = UIEdgeInsets(
                top: 0.0,
                left: 0.0,
                bottom: endframeKeyboard.size.height-85,
                right: 0.0
            )
    view.layoutIfNeeded()
}

@objc func handleKeyboardWillHide()  {
    textfeld.contentInset = .zero
    view.layoutIfNeeded()
}


//**************************
// MARK: - Views
//**************************


@IBOutlet weak var textfeld: UITextView!

Unfortunately the inset-size is not changed, when the keyboard appears and the text is partly hidden. Has anyone an idea, why it is not working?

Thanks for your support

I could not come up with a solution by using content inset but I can suggest another way.

If you add bottom constraint to the textView and create outlet for that, you can change its constant value in notifications;

@objc func handleKeyboardDidShow(notification: NSNotification) {
    guard let endframeKeyboard = notification
                .userInfo![UIResponder.keyboardFrameEndUserInfoKey]
                as? CGRect else { return }
    textViewBottomConstraint.constant = endframeKeyboard.size.height-85
}

@objc func handleKeyboardWillHide()  {
    textViewBottomConstraint.constant =  // set the previous value here
}

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