如何在按下回车键时以编程方式关闭键盘iOS


105

我以UITextField编程方式创建了UITextFieldviewController属性。我需要用返回键和屏幕上的触摸关闭键盘。我可以取消触摸屏,但是按回车键不起作用。

我已经看到了如何使用情节提要和如何UITextField直接分配和初始化对象而不将其创建为属性来进行操作。有可能吗?

。H

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

@property (strong, atomic) UITextField *username;

@end

.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor blueColor];
    self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
    self.username.placeholder = @"Enter your username";
    self.username.backgroundColor = [UIColor whiteColor];
    self.username.borderStyle = UITextBorderStyleRoundedRect;
    if (self.username.placeholder != nil) {
        self.username.clearsOnBeginEditing = NO;
    }
    _username.delegate = self; 
    
    [self.view addSubview:self.username];
    [_username resignFirstResponder];
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesBegan:withEvent:");
    [self.view endEditing:YES];
    [super touchesBegan:touches withEvent:event];
}

@end

Answers:


265

简单的方法是将的委托连接UITextField到self(self.mytestField.delegate = self),然后textFieldShouldReturn使用[textField resignFirstResponder];

关闭键盘的另一种方法如下:

[self.view endEditing:YES];

放在[self.view endEditing:YES];您要关闭键盘的位置(“按钮”事件,“触摸”事件等)。


但是,当我连接代表时,会收到警告和/或错误。我以前见过你的方法,但是由于某种原因无法使其正常工作。这些方法是否可以在viewDidLoad中使用?
noobsmcgoobs

1
如果在尝试将textField委托设置为self时遇到错误,则可能未将UITextFieldDelegate添加到类定义中。具体来说...类ViewController:UIViewController,UITextFieldDelegate {...
TimWhiting

29

添加这样的委托方法UITextField

@interface MyController : UIViewController <UITextFieldDelegate>

并设置您的textField.delegate = self;然后添加两个委托方法UITextField

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{   
    return YES;
}

// It is important for you to hide the keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

我们应该补充,只有当您的控制器实现UITextFieldDelegate时,上述内容才有效: @interface MyController : UIViewController <UITextFieldDelegate>
DerWOK 2013年

@iPatel我将这两个方法放入其中,并且还在viewDidLoad中添加了self.username.delegate = self和[self.username resignFirstResponder]。这适用于我需要的两种情况。那是正常的还是我使用了太多的代码?
noobsmcgoobs

26

//通过触摸背景来隐藏键盘

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self view] endEditing:YES];
}

24

只需快速使用它即可关闭键盘:

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)

迅捷3

UIApplication.shared.sendAction(#selector(UIResponder.resign‌​FirstResponder), to: nil, from: nil, for: nil)

SWIFT 3UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
miff 17-4-17

17

SWIFT 4:

self.view.endEditing(true)

要么

将文本字段的委托设置为当前的viewcontroller,然后:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true

}

目标C:

[self.view endEditing:YES];

要么

将文本字段的委托设置为当前的viewcontroller,然后:

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

    return YES;
}

9

在应用程序委托中,您可以编写

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.window endEditing:YES];
}

使用这种方式,您可以不必编写过多的代码。


7

尝试了解一下iOS视图层次结构中的第一响应者。当您在文本框内触摸(或以becomeFirstResponder编程方式将其传递给消息时)变为活动状态(或第一响应者)时,它将显示键盘。因此,要将您的文本字段从第一响应者中删除,您应该在resignFirstResponder此处传递消息。

[textField resignFirstResponder];

并且要将键盘隐藏在其返回按钮上,您应该实现其委托方法textFieldShouldReturn:并传递resignFirstResponder消息。

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

7

这是我在代码中使用的内容。它就像一个魅力!

在yourviewcontroller.h中添加:

@property (nonatomic) UITapGestureRecognizer *tapRecognizer;

现在在.m文件中,将其添加到您的ViewDidLoad函数中:

- (void)viewDidLoad {
    [super viewDidLoad];

    //Keyboard stuff
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    tapRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapRecognizer];
}

另外,在.m文件中添加以下功能:

- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
    [self.view endEditing:YES];
}

1
只要记住action:@selector应该在您执行endEditing的地方调用相同的方法名称即可,在这种情况下为“ handleSingleTap:”
Marcos Reboucas 2015年

4

要在弹出键盘后关闭键盘,有2种情况

  1. 当UITextField 在UIScrollView内时

  2. 当UITextField 在UIScrollView之外时

2.当UITextField在UIScrollView外部时,覆盖UIViewController子类中的方法

您还必须为所有UITextView添加委托

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
  1. 滚动视图中,在外部轻按将不会触发任何事件,因此在这种情况下,请使用Tap Gesture Recognizer,为滚动视图拖放UITapGesture为其创建IBAction

要创建IBAction,请按ctrl键并单击UITapGesture并将其拖动到viewcontroller的.h文件中。

在这里,我将tappedEvent命名为我的动作名称

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

给定的上述信息来源于以下链接,如果您不了解上述数据,请参考以获取更多信息或与我联系。

http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/


谢谢。您的回答对我有所帮助。
Archit Kapoor

4

为一组的UITextView内部A S ViewController

斯威夫特3.0

for view in view.subviews {
    if view is UITextField {
        view.resignFirstResponder()
    }
}

目标C

// hide keyboard before dismiss
for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        // no need to cast
        [view resignFirstResponder];
    }
}


3

由于标签仅表示iOS,我将发布Swift 1.2和iOs 8.4的答案,因此请将它们添加到视图控制器swift类中:

// MARK: - Close keyboard when touching somewhere else
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    self.view.endEditing(true)

}

// MARK: - Close keyboard when return pressed
func textFieldShouldReturn(textField: UITextField!) -> Bool {

    textField.resignFirstResponder()

    return true
}
// MARK: -

同样不要忘记在类声明中添加UITextFieldDelegate并将您的文本字段委托设置为self(视图)。


3

在Swift 3中

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

要么

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == yourtextfieldName
        {
            self.resignFirstResponder()
            self.view.endEditing(true)
        }
    }

2

因此,这是我在触摸背景或返回后将其关闭的方法。我必须在viewDidLoad中添加委托= self,然后再在.m文件中添加委托方法。

.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>


@property (strong, atomic) UITextField *username;

@end

.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor = [UIColor blueColor];
    self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
    self.username.placeholder = @"Enter your username";
    self.username.backgroundColor = [UIColor whiteColor];
    self.username.borderStyle = UITextBorderStyleRoundedRect;
    if (self.username.placeholder != nil) {
        self.username.clearsOnBeginEditing = NO;
    }
    self.username.delegate = self;
    [self.username resignFirstResponder];
    [self.view addSubview:self.username];


}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}



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

@end

2

只需在Objective-C中使用此命令即可关闭键盘:

[[UIApplication sharedApplication].keyWindow endEditing:YES];

1

首先,您需要在.h文件中添加textfield delegete。如果未声明 (BOOL)textFieldShouldReturn:(UITextField *)textField未调用此方法,则首先添加委托并将键盘隐藏代码写入该方法。

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

试试这个


0

添加代理:UITextFieldDelegate

@interface ViewController : UIViewController <UITextFieldDelegate>

然后添加此委托方法

//这应该完美

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

0
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
    if ([obj isKindOfClass:[UITextField class]]) {
        [obj resignFirstResponder];
    }
}];
}

当您在屏幕上使用多个文本字段时,使用这种方法,您不必每次都像提到文本字段一样

[textField1 resignFirstResponder];
[textField2 resignFirstResponder];

0

迅捷2:

这是每件事要做的事!

使用Done或按钮关闭键盘Touch outSideNext以转到下一个输入。

在StoryBoard中首先将TextFiled更改Return KeyNext

override func viewDidLoad() {
  txtBillIdentifier.delegate = self
  txtBillIdentifier.tag = 1
  txtPayIdentifier.delegate  = self
  txtPayIdentifier.tag  = 2

  let tap = UITapGestureRecognizer(target: self, action: "onTouchGesture")
  self.view.addGestureRecognizer(tap)

}

func textFieldShouldReturn(textField: UITextField) -> Bool {
   if(textField.returnKeyType == UIReturnKeyType.Default) {
       if let next = textField.superview?.viewWithTag(textField.tag+1) as? UITextField {
           next.becomeFirstResponder()
           return false
       }
   }
   textField.resignFirstResponder()
   return false
}

func onTouchGesture(){
    self.view.endEditing(true)
}

0

如果您不知道当前的视图控制器或文本视图,则可以使用响应者链:

UIApplication.shared.sendAction(#selector(UIView.endEditing(_:)), to:nil, from:nil, for:nil)

0

快速3-4我固定像

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return false
}

只需在课堂上的任何地方复制粘贴。如果您希望所有UItextfield都一样工作,或者只有一个UItextfield,则此解决方案才有效!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.