出现键盘时调整 UITextView 的大小

问题描述

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

我使用此处显示解决方案进行了尝试:Resize the UITextView when keyboard appears

相应地,我的代码如下:

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 添加底部约束并为其创建出口,则可以在通知中更改其常量值;

break;