如何在 textview 中输入后关闭 tableView 中的键盘

How to dismiss keyboard in a tableView after typing in textview

在我的应用程序中,我有一个 UITableView,它在第一个单元格中包含 UITextView,在其他单元格中仅包含 UILabels.

如何在 UITableView 中键入内容后关闭键盘?我想在点击其他单元格或滚动表格视图时随时关闭它。

可以使用符合UIScrollViewDelegateUITableViewDelegate来实现:

func scrollViewWillBeginDragging(scrollView: UIScrollView) {
     dismissKeyboard()
}

func dismissKeyboard(){
     self.view.endEditing(true)
}

//Add to viewDidLoad:
var tapGesture = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
tableView.addGestureRecognizer(tapGesture)

//Or since you wanted to dismiss when another cell is selected use:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
     dismissKeyboard()
}

这是最简单最简单的方法 我是如何通过 IB 做到这一点的。


在这里你可以设置属性

或者如果你想通过编程然后

self.tableView.keyboardDismissMode = .onDrag