UITextView完成按钮操作-按回车键

3

使用UITextView,如何知道键盘上的“完成”或其他按钮被按下了?

我需要在textViewDidChange中查看每个字符吗?如果是这样,需要查找什么?

IB选择了UITextView:

enter image description here

3个回答

6
我刚刚测试了一下,似乎满足你的要求:
class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var myTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
       myTextView.delegate = self
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
    {
        if(text == "\n")
        {
            view.endEditing(true)
            return false
        }
        else
        {
            return true
        }
    }
}

从意义上讲,如果您已经指定了自己是调用的委托,则无关紧要。可以在Interface Builder中选择“完成”,“前往”,“下一个”或者通过编程设置。 - Martin Muldoon
@ChrisG。你设置了代理吗? - Martin Muldoon

3

可以在 textViewDidChange 中查找换行符"\n"来实现。

否则,更好的做法是使用 func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String) 并检查 replacementText == "\n"

示例:

func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String){
    if replacementText == "\n"{
        // do your stuff here
        // return false here, if you want to disable user from adding newline
    }
    // otherwise, it will return true and the text will be replaced
    return true
}

谢谢,但那将会对“输入”和“确认”按钮生效。我需要用户能够添加新行。另外它是“\n” :-) - Chris G.
哪个“确定”按钮?你是指“完成”按钮吗? 据我所知,这会在UITextView中产生“\n”。 - ramacode
1
是的,我的答案仍然是一样的。回车键会产生“\n”。是否允许用户添加新行取决于您在func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String)中返回什么。 - ramacode

-2

使用 textFieldShouldReturn: 方法

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
   if textField == yourTextField {
      //do something
   }

   return true
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接