按返回时如何以编程方式关闭键盘iOS [英] How to dismiss keyboard iOS programmatically when pressing return
问题描述
我创建了一个 UITextField
,以编程方式使 UITextField
成为viewController的一个属性。我需要通过屏幕上的返回和触摸来关闭键盘。我能够让屏幕触摸解除,但按下返回不起作用。
I created a UITextField
programmatically making the UITextField
a property of the viewController. I need to dismiss the keyboard with the return and the touch on the screen. I was able to get the screen touch to dismiss, but pressing return is not working.
我已经看过如何使用故事板以及直接分配和初始化 UITextField
对象而不创建它作为财产。可能吗?
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?
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
@property (strong, atomic) UITextField *username;
@end
.m
.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
推荐答案
简单的方法是将 UITextField
的委托连接到self( self.mytestField.delegate = self
)并使用 [textField resignFirstResponder]解除方法
textFieldShouldReturn
中的键盘;
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];
解雇键盘的另一种方法如下:
Another way to dismiss the keyboard is the following:
[self.view endEditing:YES];
put [self.view endEditing:YES];
您想要解除键盘的位置(按钮事件,触摸事件等)。
Put [self.view endEditing:YES];
where you would like to dismiss the keyboard (Button event, Touch event, etc.).
这篇关于按返回时如何以编程方式关闭键盘iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!