出现键盘时调整 UITextView 的大小

Resize UITextView when keyboard appears

我尝试在出现键盘时调整 UITextView 字段的高度(iOS 14.2,Xcode 12.3)。 UITextView底部到保存区域的距离为90,因此下半部分被键盘隐藏,编辑时看不到。

我尝试了这里显示的解决方案:

据此,我的代码如下:

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!

不幸的是,当键盘出现并且部分文本被隐藏时,插图大小没有改变。 有谁知道为什么它不起作用?

感谢您的支持

我无法通过使用内容插图提出解决方案,但我可以建议另一种方法。

如果向 textView 添加 bottom 约束并为其创建 outlet,则可以在通知中更改其常量值;

@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
}