我知道已经有很多类似的问题了,但是在看了其中的许多问题之后,它们涉及UITextField,因此涉及UITextFieldDelegate的textFieldShouldReturn方法。但是,我有一个UITextView,而不是UITextField,我想知道用户何时点击了相关键盘上的完成按钮。
我有一个表格视图,当用户点击其中一行时,表格进入编辑模式,用户可以在单元格内的 UITextView 中输入文本。下面是一些代码:
包含文本视图的单元格
class ReportTextEntryCell : UITableViewCell
{
@IBOutlet weak var commentsTextView: UITextView!
}
单元格的创建,从cellForRowAt
func getTextEntryCell() -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "TextEntryCellID") as? ReportTextEntryCell
cell!.commentsTextView.delegate = self
cell!.commentsTextView.keyboardAppearance = .light
cell!.commentsTextView.keyboardType = UIKeyboardType.default
cell!.commentsTextView.tintColor = UIColor.black
cell!.commentsTextView.returnKeyType = .done
return cell!
}
出现键盘,用户可以键入文本。
表视图控制器实现UITextViewDelegate
,textViewShouldBeginEditing
和shouldChangeTextIn
都被调用。但我预计当用户点击键盘上的"完成"按钮时会调用textViewShouldEndEditing
,但事实并非如此。
我如何知道用户何时点击完成按钮?
继承UITextViewDelegate
并为textView
设置delegate
,然后可以使用以下内容:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "n" {
// User pressed Done
textView.resignFirstResponder()
return false
}
return true
}