簡體   English   中英

如何在模態呈現的 UITableView 上關閉 UITextView 上的鍵盤

[英]How to dismiss the keyboard on a UITextView on a modally presented UITableView

晚上好,

我試圖在模態呈現的 UITableView 上關閉鍵盤。 UITextView被創建為UINib並在UITableView注冊。

我試圖在故事板中將鍵盤設置為“Dismiss On Drag”,但沒有任何效果。 我還編寫了以下代碼並將UITextFieldDelegate連接到UINib

這是UITextView Nib 中的代碼。

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
          if(text == "\n") {
              textView.resignFirstResponder()
              return false
          }
          return true
      }

查看確實加載:

override func awakeFromNib() {
    super.awakeFromNib()
    textView.delegate = self
}

使用滾動視圖,這是一個例子,因為我不太明白你在你的項目中做什么......首先將包含你的 textView 的控制器設置為 UIScrollViewDelegate,然后聲明你的對象及其屬性:

class YourController: UIViewController, UIScrollViewDelegate {

let scrollView2: UIScrollView = {
    let scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    return scrollView
}()

let textV: UITextView = {
    let v = UITextView()
    v.backgroundColor = .yourColor
    v.isUserInteractionEnabled = true
    v.textColor = .white
    v.font = .systemFont(ofSize: 20, weight: .regular)
    v.translatesAutoresizingMaskIntoConstraints = false
    v.heightAnchor.constraint(equalToConstant: 1000).isActive = true // assign here the text view height to allow your scrollview to scroll
    return v
}()

override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    scrollView2.delegate = self

    setupConstraints() // call the function for constraints
}

下面 viewDidLoad 寫約束函數:

fileprivate func setupConstraints() {
    
    view.addSubview(scrollView2)
    scrollView2.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    scrollView2.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    scrollView2.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView2.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    
    scrollView2.addSubview(textV)
    textV.leadingAnchor.constraint(equalTo: scrollView2.leadingAnchor).isActive = true
    textV.trailingAnchor.constraint(equalTo: scrollView2.trailingAnchor).isActive = true
    textV.topAnchor.constraint(equalTo: scrollView2.topAnchor).isActive = true
    textV.bottomAnchor.constraint(equalTo: scrollView2.bottomAnchor).isActive = true
    // this is important for scrolling
    textV.widthAnchor.constraint(equalTo: scrollView2.widthAnchor).isActive = true
}

現在調用 scrollViewWillBeginDragging 並將交互模式分配給您的滾動視圖 keyboardDismissMode:

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    scrollView2.keyboardDismissMode = .interactive
}

這是結果

在此處輸入圖片說明

暫無
暫無

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

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