[英]How to perform an action when the user hits the keyboard's done button for a UITextView
I know there are lots of similar questions about this already, but after looking at many of them they are involving UITextField and consequently UITextFieldDelegate's textFieldShouldReturn method. 我知道已经有很多类似的问题,但是在研究了许多问题之后,它们都涉及UITextField,因此也涉及UITextFieldDelegate的textFieldShouldReturn方法。 However I have a UITextView, not a UITextField, and I want to know when the user has hit the done button on the associated keyboard.
但是,我有一个UITextView,而不是UITextField,我想知道用户何时单击了相关键盘上的完成按钮。
I have a table view where when the user taps on one of the rows the table enters an editing mode and the user can enter text into a UITextView which is within a cell. 我有一个表格视图,当用户点击其中一行时,表格进入编辑模式,并且用户可以将文本输入到单元格内的UITextView中。 Here is some code:
这是一些代码:
The cell containing the text view 包含文本视图的单元格
class ReportTextEntryCell : UITableViewCell
{
@IBOutlet weak var commentsTextView: UITextView!
}
The creation of the cell, which is called from within cellForRowAt 单元的创建,从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!
}
The keyboard appears, the user can type text. 出现键盘,用户可以键入文本。
The table view controller implements UITextViewDelegate
and textViewShouldBeginEditing
and shouldChangeTextIn
are both invoked. 表视图控制器实现
UITextViewDelegate
和textViewShouldBeginEditing
和shouldChangeTextIn
都调用。 But I was expecting textViewShouldEndEditing
would be called when the user taps the Done button on the keyboard, but it is not. 但是我期望当用户点击键盘上的“完成”按钮时会调用
textViewShouldEndEditing
,但事实并非如此。
How can I know when the user hits the done button? 我怎么知道用户何时点击完成按钮?
You need to inherit the UITextViewDelegate
and set the delegate
for your textView
and then you can use the following: 你需要继承
UITextViewDelegate
并设置delegate
为您textView
,然后你可以使用以下命令:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
// User pressed Done
textView.resignFirstResponder()
return false
}
return true
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.