objective-c 如何使用返回键关闭 UITextView 的键盘?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/703754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:20:03  来源:igfitidea点击:

How to dismiss keyboard for UITextView with return key?

iphoneobjective-ckeyboarduitextviewiphone-softkeyboard

提问by Chilly Zhong

In IB's library, the introduction tells us that when the returnkey is pressed, the keyboard for UITextViewwill disappear. But actually the returnkey can only act as '\n'.

在IB的库中,介绍告诉我们当return按键被按下时,键盘UITextView会消失。但实际上return密钥只能充当'\n'。

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

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

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

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

采纳答案by lostInTransit

UITextViewdoes not have any methods which will be called when the user hits the return key. If you want the user to be able to add only one line of text, use a UITextField. Hitting the return and hiding the keyboard for a UITextViewdoes not follow the interface guidelines.

UITextView没有任何方法可以在用户点击返回键时调用。如果您希望用户只能添加一行文本,请使用UITextField. 按回车键和隐藏键盘UITextView不遵循界面指南。

Even then if you want to do this, implement the textView:shouldChangeTextInRange:replacementText:method of UITextViewDelegateand in that check if the replacement text is \n, hide the keyboard.

即便如此,如果您想这样做,请实现textView:shouldChangeTextInRange:replacementText:方法UITextViewDelegate并在该方法中检查替换文本是否为\n,隐藏键盘。

There might be other ways but I am not aware of any.

可能还有其他方法,但我不知道任何方法。

回答by samvermette

Figured I would post the snippet right here instead:

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

Make sure you declare support for the UITextViewDelegateprotocol.

确保您声明支持该UITextViewDelegate协议。

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

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

    return YES;
}

Swift 4.0 update:

斯威夫特 4.0 更新:

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

回答by ribeto

I know this has been answered already but I don't really like using the string literal for the newline so here is what I did.

我知道这已经得到了回答,但我真的不喜欢使用字符串文字作为换行符,所以这就是我所做的。

- (BOOL)textView:(UITextView *)txtView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if( [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound ) {
        return YES;
    }

    [txtView resignFirstResponder];
    return NO;
}

Swift 4.0 update:

斯威夫特 4.0 更新:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text as NSString).rangeOfCharacter(from: CharacterSet.newlines).location == NSNotFound {
    return true
}
txtView.resignFirstResponder()
return false
}

回答by josebama

I know this has been answered a lot of times, but here are my two cents to the issue.

我知道这已经被回答了很多次,但这是我对这个问题的两分钱。

I found the answers by samvermetteand ribetoreally useful, and also the comment by maxpowerin the ribeto's answer. But there is a problem with those approaches. The problem that mattmentions in the samvermette's answer and it's that if the user wants to paste something with a line break inside it, the keyboard would hide without pasting anything.

我发现samvermetteribeto的答案非常有用,还有maxpowerribeto的答案中的评论。但是这些方法存在问题。mattsamvermette的回答中提到的问题是,如果用户想要粘贴其中带有换行符的内容,键盘将隐藏而不粘贴任何内容。

So my approach is a mixture of the three above mentioned solutions and only checking if the string entered is a new line when the length of the string is 1 so we make sure the user is typing instead of pasting.

所以我的方法是上述三种解决方案的混合,并且仅在字符串长度为 1 时检查输入的字符串是否为新行,因此我们确保用户正在输入而不是粘贴。

Here is what I have done:

这是我所做的:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSRange resultRange = [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet] options:NSBackwardsSearch];
    if ([text length] == 1 && resultRange.location != NSNotFound) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}

回答by TMilligan

A more elegant way is to dismiss the keyboard when the user taps somewhere outside of the keyboard's frame.

更优雅的方法是当用户点击键盘框架之外的某个地方时关闭键盘。

First, set your ViewController's view to the class "UIControl" in the identity inspector in UIBuilder. Control-drag the view into the ViewController's header file and link it as an action with the event as Touch Up Inside, such as:

首先,在 UIBuilder 的身份检查器中将 ViewController 的视图设置为“UIControl”类。按住 Control 键将视图拖入 ViewController 的头文件中,并将其作为一个动作链接到作为 Touch Up Inside 的事件,例如:

ViewController.h

视图控制器.h

-(IBAction)dismissKeyboardOnTap:(id)sender;

In the main ViewController file, ViewController.m:

在主 ViewController 文件 ViewController.m 中:

-(IBAction)dismissKeyboardOnTap:(id)sender
    {
         [[self view] endEditing:YES];
    }

You can require a double tap or long touch using similar techniques. You may need to set your ViewController to be a UITextViewDelegate and connect the TextView to the ViewController. This method works for both UITextView and UITextField.

您可以使用类似的技术要求双击或长按。您可能需要将 ViewController 设置为 UITextViewDelegate 并将 TextView 连接到 ViewController。此方法适用于 UITextView 和 UITextField。

Source: Big Nerd Ranch

资料来源:大书呆子牧场

EDIT: I'd also like to add that if you are using a UIScrollView, the above technique may not work as easily through the Interface Builder. In that case, you could use a UIGestureRecognizer and call the [[self view] endEditing:YES] method within it instead. An example would be:

编辑:我还想补充一点,如果您使用的是 UIScrollView,则上述技术可能无法通过 Interface Builder 轻松工作。在这种情况下,您可以使用 UIGestureRecognizer 并在其中调用 [[self view] endEditing:YES] 方法。一个例子是:

-(void)ViewDidLoad{
    ....
    UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] 
        initWithTarget:self action:@selector(tap:)];
    [self.view addGestureRecognizer: tapRec];
    ....
}

-(void)tap:(UITapGestureRecognizer *)tapRec{
    [[self view] endEditing: YES];
}

When the user taps outside of the keyboard and does not tap an entry space, the keyboard will dismiss.

当用户在键盘外部点击并且没有点击输入空间时,键盘将关闭。

回答by Alexander Volkov

Add this method in your view controller.

在您的视图控制器中添加此方法。

Swift:

斯威夫特

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

This method also can be helpful for you:

这个方法对你也有帮助:

/**
Dismiss keyboard when tapped outside the keyboard or textView

:param: touches the touches
:param: event   the related event
*/
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if let touch = touches.anyObject() as? UITouch {
        if touch.phase == UITouchPhase.Began {
            textField?.resignFirstResponder()
        }
    }
}

回答by Vineesh TP

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"])
        [textView resignFirstResponder];
    return YES;
}

yourtextView.delegate=self;

Also add UITextViewDelegate

还添加 UITextViewDelegate

Don't forget to confirm protocol

不要忘记确认协议

IF you didn't add if([text isEqualToString:@"\n"])you can't edit

如果您没有添加if([text isEqualToString:@"\n"]),则无法编辑

回答by g212gs

There is another solution while using with uitextview, You can add toolbar as InputAccessoryView in "textViewShouldBeginEditing", and from this toolbar's done button you can dismiss keyboard, the code for this is following:

与 uitextview 一起使用时还有另一种解决方案,您可以在“textViewShouldBeginEditing”中将工具栏添加为 InputAccessoryView,从该工具栏的完成按钮中您可以关闭键盘,代码如下:

In viewDidLoad

在视图中加载

toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; //toolbar is uitoolbar object
toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(btnClickedDone:)];
[toolBar setItems:[NSArray arrayWithObject:btnDone]];

In textviewdelegate method

在 textviewdelegate 方法中

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
     [textView setInputAccessoryView:toolBar];
     return YES;
}

In action of Button Done which is in toolbar is following:

在工具栏中的按钮完成的操作如下:

-(IBAction)btnClickedDone:(id)sender
{
    [self.view endEditing:YES];
}

回答by Puneet Kohli

I found the answer by josebamato be the most complete and clean answer available in this thread.

我发现josebama 的答案是该线程中最完整、最干净的答案。

Below is the Swift 4syntax for it:

下面是它的Swift 4语法:

func textView(_ textView: UITextView, shouldChangeTextIn _: NSRange, replacementText text: String) -> Bool {
    let resultRange = text.rangeOfCharacter(from: CharacterSet.newlines, options: .backwards)
    if text.count == 1 && resultRange != nil {
        textView.resignFirstResponder()
        // Do any additional stuff here
        return false
    }
    return true
}

回答by Eduardo Oliveros Acosta

swift

迅速

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

and configure

并配置