如何使用返回键关闭 UITextView 的键盘? [英] How to dismiss keyboard for UITextView with return key?

查看:33
本文介绍了如何使用返回键关闭 UITextView 的键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在IB的库中,介绍告诉我们,当按下return键时,UITextView的键盘就会消失.但实际上return键只能充当' '.

In IB's library, the introduction tells us that when the return key is pressed, the keyboard for UITextView will disappear. But actually the return key can only act as ' '.

我可以添加一个按钮并使用 [txtView resignFirstResponder] 隐藏键盘.

I can add a button and use [txtView resignFirstResponder] to hide the keyboard.

但是有没有办法为键盘中的 return 键添加动作,这样我就不需要添加 UIButton?

But is there a way to add the action for the return key in keyboard so that I needn't add UIButton?

推荐答案

我想我会在这里发布代码片段:

Figured I would post the snippet right here instead:

确保您声明支持 UITextViewDelegate 协议.

Make sure you declare support for the UITextViewDelegate protocol.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    if([text isEqualToString:@"
"]) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}

Swift 4.0 更新:

Swift 4.0 update:

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

这篇关于如何使用返回键关闭 UITextView 的键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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