ios Xcode 4.2 按下“完成/返回”按钮时如何隐藏文本框键盘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10965357/
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-08-30 18:42:03  来源:igfitidea点击:

How to hide Textbox Keyboard when "Done / Return" Button is pressed Xcode 4.2

iphoneiosxcode4.2

提问by Talon

I created a Text Field in Interface Builder. I set it's "Return Key" to Done. This is a one line only input (so it wont need multiple lines).

我在 Interface Builder 中创建了一个文本字段。我将它的“返回键”设置为完成。这是一个只有一行的输入(所以它不需要多行)。

How do I hide the virtual keyboard when the user taps the done button?

当用户点击完成按钮时如何隐藏虚拟键盘?

回答by Paul Hunter

Implement the delegate method UITextFieldDelegate, then:

实现委托方法UITextFieldDelegate,然后:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.yourIBtextField.delegate = self;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

回答by Himanshu padia

UITextView does not have any methods which will be called when the user hits the return key.

UITextView 没有任何方法可以在用户点击返回键时调用。

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

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

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

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

Make sure you declare support for the UITextViewDelegate protocol.

确保声明对 UITextViewDelegate 协议的支持。

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

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

I hope it will helps a lot.

我希望它会很有帮助。

回答by ixi

Make category on UIViewController with next method

使用 next 方法在 UIViewController 上创建类别

- (void)hideKeyboard
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)
                                               to:nil
                                             from:nil
                                         forEvent:nil];
}