如何解除键盘 iOS 编程时按返回

我通过编程方式创建了一个 UITextField,使 UITextField成为 viewController 的一个属性。我需要解除键盘与返回和触摸屏幕上。我可以让屏幕触摸消失,但按回车不工作。

I've seen how to do it with storyboards and by allocating and initializing the UITextField object directly without creating it as a property. Possible to do?

。 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
190302 次浏览

Add a delegate method of UITextField like this:

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

首先,您需要在.h 文件中添加文本字段委托。如果没有声明 这个方法没有被调用。所以首先添加委托并将键盘隐藏代码写入该方法。

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

试试这个。

试着了解一下 iOS 视图层次结构中的第一响应者是什么。当您的文本字段变为活动的(或第一响应者) ,当您触摸内部(或传递它的消息 becomeFirstResponder编程) ,它显示键盘。因此,要从第一个响应者中删除文本字段,您应该将消息 resignFirstResponder传递给它。

[textField resignFirstResponder];

And to hide the keyboard on its return button, you should implement its delegate method textFieldShouldReturn: and pass the resignFirstResponder message.

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

添加委托: UITextField 委托

@interface ViewController : UIViewController <UITextFieldDelegate>

and then add this delegate method

//这应该会很完美

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

The simple way is to connect the delegate of UITextField to self (self.mytestField.delegate = self) and dismiss the keyboard in the method textFieldShouldReturn using [textField resignFirstResponder];

取消键盘的另一种方法是:

目标 C

[self.view endEditing:YES];

斯威夫特:

self.view.endEditing(true)

[self.view endEditing:YES];放在你想关闭键盘的地方(按钮事件,触摸事件,等等)。

所以这里是我做了什么,使它在触摸背景或返回后消除。我必须在 viewDidLoad 中添加 committee = 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

//Hide keyBoard by touching background in view

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

对于 ViewController内的一组 UITextView:

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

我知道其他人已经回答了这个问题,但是我发现另一篇文章也没有涉及背景事件—— tableview 或 scrollview。

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

下面是我在代码中使用的方法,非常有效!

In yourviewcontroller.h add:

@property (nonatomic) UITapGestureRecognizer *tapRecognizer;

Now in the .m file, add this to your ViewDidLoad function:

- (void)viewDidLoad {
[super viewDidLoad];


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

Also, add this function in the .m file:

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

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

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

use this way, you can don`t write too much code.

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

当你在屏幕上使用多个文本字段时 使用这种方法,您不需要每次都提到 textfield,比如

[textField1 resignFirstResponder];
[textField2 resignFirstResponder];

因为这些标签只说 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: -

也不要忘记在类声明中添加 UITextFieldCommittee,并将文本字段委托设置为 self (视图)。

斯威夫特2:

每件事都是这么做的!

关闭键盘与 Done按钮或 Touch outSideNext去下一个输入。

在故事板中首次将文本文件 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)
}

简单地使用这个快速键盘:

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)

要在键盘弹出后取消键盘,有 2 cases,

  1. 当 UITextField 为 在 UIScrollView 中

  2. 当 UITextField 为 在 UIScrollView 之外

2. 当 UITextField 位于 UIScrollView 之外时 重写 UIViewController 子类中的方法

你也必须 为所有 UITextView 添加委托

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
  1. 滚动视图,在外部点击不会触发任何事件中,所以在这种情况下 使用轻敲手势识别器, 拖放一个用于滚动视图和 create an IBAction for itUITapGesture

to create a IBAction, press ctrl+ click the UITapGesture and drag it to the .h file of viewcontroller.

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

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

以上资料来自以下连结,如你不明白以上资料,请参阅更多资料或与我联络。

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

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

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

对于快速的3-4强我固定喜欢

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

复制粘贴到课堂上的任何地方。如果您希望所有 UItextfield 工作都一样,或者只有一个 UItextfield 工作,那么这个解决方案可以正常工作!

《雨燕3》

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

OR

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

SWIFT 4:

self.view.endEditing(true)

或者

Set text field's delegate to current viewcontroller and then:

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


textField.resignFirstResponder()


return true


}

目标 C:

[self.view endEditing:YES];

or

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

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


return YES;
}

只需在 Objective-C 中使用这个命令就可以解雇键盘:

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