【问题标题】:How to perform an action when the user hits the keyboard's done button for a UITextView当用户点击 UITextView 的键盘完成按钮时如何执行操作
【发布时间】:2017-06-09 17:36:09
【问题描述】:

我知道已经有很多类似的问题,但是在查看了其中许多之后,它们涉及 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!
}

键盘出现,用户可以输入文字。

表格视图控制器实现UITextViewDelegatetextViewShouldBeginEditingshouldChangeTextIn 都被调用。 但我原以为textViewShouldEndEditing 会在用户点击键盘上的“完成”按钮时被调用,但事实并非如此。

我如何知道用户何时点击了完成按钮?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您需要继承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
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2011-06-18
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      相关资源
      最近更新 更多