簡體   English   中英

出現鍵盤時調整 UITextView 的大小

[英]Resize UITextView when keyboard appears

當鍵盤出現時,我嘗試調整 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 並為此創建出口,則可以在通知中更改其常量值;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM