【问题标题】:How to dismiss keyboard iOS programmatically when pressing return按下回车键时如何以编程方式关闭键盘iOS
【发布时间】:2013-09-16 07:36:39
【问题描述】:

我以编程方式创建了一个UITextField,使UITextField 成为viewController 的一个属性。我需要通过返回和触摸屏幕来关闭键盘。我能够让屏幕触摸消失,但按回车键不起作用。

我已经了解了如何使用情节提要以及直接分配和初始化 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

【问题讨论】:

标签: ios keyboard uitextfield


【解决方案1】:

简单的方法是将UITextField的委托连接到自己(self.mytestField.delegate = self)并使用[textField resignFirstResponder];在方法textFieldShouldReturn中关闭键盘

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

Objective-C

[self.view endEditing:YES];

斯威夫特:

self.view.endEditing(true)

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

【讨论】:

  • 当我连接代理时,我收到警告和/或错误。我以前见过你的方法,但由于某种原因无法让它工作。这些方法会进入 viewDidLoad 吗?
  • 如果您在尝试将 textField 委托设置为 self 时遇到错误,那么您可能没有将 UITextFieldDelegate 添加到类定义中。具体来说... class ViewController: UIViewController, UITextFieldDelegate { ...
【解决方案2】:

像这样添加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 &lt;UITextFieldDelegate&gt;
  • @iPatel 我把这两个方法放进去,还在 viewDidLoad 中添加了 self.username.delegate = self 和 [self.username resignFirstResponder]。这适用于我需要的两种情况。这是正常的还是我使用了太多的代码?
【解决方案3】:

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

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 3 UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
【解决方案4】:

//通过在视图中触摸背景来隐藏键盘

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

【讨论】:

    【解决方案5】:

    SWIFT 4:

    self.view.endEditing(true)
    

    将文本字段的委托设置为当前视图控制器,然后:

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    
        textField.resignFirstResponder()
    
        return true
    
    }
    

    目标-C:

    [self.view endEditing:YES];
    

    将文本字段的委托设置为当前视图控制器,然后:

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

    【讨论】:

      【解决方案6】:

      在 App Delegate 中可以写

      - (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;
        }
        

        【讨论】:

          【解决方案8】:

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

          在 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];
          }
          

          【讨论】:

          • 只要记住动作:@selector 应该调用与您执行 endEditing 的方法名称相同的方法名称:YES,在本例中为“handleSingleTap:”
          【解决方案9】:

          对于ViewController内的一组UITextViews:

          Swift 3.0

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

          Objective-C

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

          【讨论】:

            【解决方案10】:

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

            1. 当 UITextField 在 UIScrollView 内时

            2. 当 UITextField 在 UIScrollView 之外时

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

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

            - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
                [self.view endEditing:YES];
            }
            
            1. 滚动视图中,点击外部不会触发任何事件,因此在这种情况下使用点击手势识别器, 为滚动视图拖放 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/

            【讨论】:

            • 谢谢。你的回答帮助了我..!
            【解决方案11】:

            我知道其他人已经回答了这个问题,但我发现另一篇文章也涵盖了无背景事件 - 表格视图或滚动视图。

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

            【讨论】:

              【解决方案12】:

              由于标签只说 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(视图)。

              【讨论】:

                【解决方案13】:

                IN 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)
                        }
                    }
                

                【讨论】:

                  【解决方案14】:

                  首先您需要在 .h 文件中添加文本字段删除。如果不声明 (BOOL)textFieldShouldReturn:(UITextField *)textField这个方法没有被调用。所以首先添加委托并将键盘隐藏代码写入该方法。

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

                  试试这个..

                  【讨论】:

                    【解决方案15】:

                    这就是我在触摸背景或返回后让它消失的方法。我必须在 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
                    

                    【讨论】:

                      【解决方案16】:

                      只需在 Objective-C 中使用它来关闭键盘:

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

                      【讨论】:

                        【解决方案17】:

                        添加委托:UITextFieldDelegate

                        @interface ViewController : UIViewController <UITextFieldDelegate>
                        

                        然后添加这个委托方法

                        // 这应该可以完美运行

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

                        【讨论】:

                          【解决方案18】:
                          - (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];
                          

                          【讨论】:

                            【解决方案19】:

                            斯威夫特 2:

                            这就是要做的每一件事!

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

                            首先在 StoryBoard 中将 TextFiled Return Key 更改为 Next

                            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)
                            }
                            

                            【讨论】:

                              【解决方案20】:

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

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

                              【讨论】:

                                【解决方案21】:

                                对于 swift 3-4 我固定喜欢

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

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

                                【讨论】:

                                  猜你喜欢
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 2011-12-16
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多