如何在模态显示的UITableView上关闭UITextView上的键盘

问题描述

晚上好

我正在尝试关闭以模态显示的UITableView上的键盘UITextView被创建为UINib,并在UITableView注册

我试图在情节提要中将键盘设置为“ dismiss On Drag”,但没有任何效果。我还编写了以下代码,并将UITextFieldDelegate连接到UINib上。

这是UITextView笔尖中的代码

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并将交互模式分配给您的scrollview keyboardDismissMode:

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

这是结果

enter image description here