按返回时如何以编程方式关闭键盘iOS

时间:2013-09-12 04:31:49

标签: ios keyboard uitextfield

我以编程方式创建了一个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

21 个答案:

答案 0 :(得分:249)

简单的方法是将UITextField的代表连接到自我(self.mytestField.delegate = self)并使用textFieldShouldReturn

关闭方法[textField resignFirstResponder];中的键盘

另一种解雇键盘的方法如下:

[self.view endEditing:YES];

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

答案 1 :(得分: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;
}

答案 2 :(得分:24)

//通过触摸视图中的背景隐藏keyBoard

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

答案 3 :(得分:19)

只需在swift中使用它来解除键盘:

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

Swift 3

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

答案 4 :(得分:10)

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

答案 5 :(得分:8)

在App Delegate中,您可以写

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

使用这种方式,你不会写太多代码。

答案 6 :(得分:6)

尝试了解第一响应者在iOS视图层次结构中的含义。当您触摸文本字段(或第一响应者)时(或以编程方式将消息传递给becomeFirstResponder),它会显示键盘。因此,要将文本字段从第一个响应者中删除,您应该将消息resignFirstResponder传递给它。

[textField resignFirstResponder];

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

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

答案 7 :(得分:6)

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

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

答案 8 :(得分:3)

对于UITextView中的一组ViewController

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

答案 9 :(得分:3)

在键盘弹出后关闭键盘, 2例

  1. 当UITextField在UIScrollView中

  2. 当UITextField在UIScrollView外

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

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

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

答案 10 :(得分:2)

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

答案 11 :(得分:2)

我知道其他人已经回答了这个问题,但是我找到了另一篇文章,其中也没有介绍任何背景事件 - tableview或scrollview。

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

答案 12 :(得分:2)

由于标签只说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 :(得分:1)

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

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

答案 14 :(得分:1)

所以这就是我在触摸背景或返回后做出的解雇。我不得不在viewDidLoad中添加delegate = 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

答案 15 :(得分:1)

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

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

尝试这个..

答案 16 :(得分:0)

Swift 2:

这就是做所有事情的方法!

使用userSchema.set('toJSON', {virtuals: true}); 按钮关闭键盘或DoneTouch outSide以转到下一个输入。

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

Next

答案 17 :(得分:0)

[textField1 resignFirstResponder];
[textField2 resignFirstResponder];

当您在屏幕中使用多个文本字段时 使用此方法,您无需每次都提及文本字段,如

public boolean onDoubleTap(MotionEvent e) {
        if (!normal) {
            restore();
        } else {
            zoomToSpot(e);
        }
        doubleclicked = true;
        return true;
    }

答案 18 :(得分:0)

如果您不了解当前的视图控制器或textview,您可以使用响应者链:

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

答案 19 :(得分:0)

for swift 3-4 我修好了

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

只需在课程的任何位置复制粘贴。如果您希望所有UItextfield都工作相同,或者您只有一个!

,则此解决方案正常工作

答案 20 :(得分:0)

添加委托:UITextFieldDelegate

@interface ViewController : UIViewController <UITextFieldDelegate>

然后添加此委托方法

//这应该可以完美地运作

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