在UITextView中迅速将“返回”按钮功能更改为“完成” [英] Change 'Return' button function to 'Done' in swift in UITextView

查看:159
本文介绍了在UITextView中迅速将“返回”按钮功能更改为“完成”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户键入时摆脱键盘的返回功能,因此没有新行,所以我希望将返回键用作完成,这样隐藏键盘。

I would like to get rid of the "return" function of the keyboard while the user is typing, so there are no new lines, so instead I would like the 'return' key to function as 'Done' so it would hide the keyboard.

我正在使用可编辑的UITextView,因此用户可以键入其帖子,并将其发布到主时间轴,但是由于我具有固定的单元格,我不希望用户能够按返回键,并且他们的帖子将超出时间范围。

I am using a UITextView, that is editable, so the user is able to type their post, and post it to the main timeline, but since I have fixed cells, I don't want the user to be able to press 'return' and their post would be out of range of the timeline.

我发现此方法适用于UITextField,但不适用于UITextView:

I found this that works with UITextField, but not with UITextView:

func textFieldShouldReturn(textField: UITextField!) -> Bool {
    textField.resignFirstResponder()  //if desired
    return true
}

所以我只想知道是否可以在UITextView中做到这一点,或者至少可以在按回车键时隐藏键盘,而不是创建新行。

So I just wanted to know if there is a way to do that in a UITextView, or at least to be able to hide the keyboard if pressed return, instead of creating a new line.

推荐答案

您可以设置文本字段的返回键类型:

You can set the return key type of the text field:

textField.returnKeyType = UIReturnKeyType.done

更新
如上所述,您绝对可以使用相同的方法将返回键设置为完成。但是,当用户按下返回键时,UITextView不提供回调。解决方法是,您可以尝试处理textView(textView:UITextView,shouldChangeTextInRange范围:NSRange,replaceText text:String)委托调用,并在检测到换行符输入时关闭键盘:

Update You can definitely use the same approach to set the return key to "Done", as mentioned above. However, UITextView doesn't provide a callback when user hits the return key. As a workaround, you can try to handle the textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) delegate call, and dismiss the keyboard when you detect the input of a new line character:

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

这篇关于在UITextView中迅速将“返回”按钮功能更改为“完成”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆