How to dismiss keyboard iOS programmatically when pressing return(按下回车键时如何以编程方式关闭键盘iOS)
问题描述
我以编程方式创建了一个 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
#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
的delegate连接到self(self.mytestField.delegate = self
) 并在方法 textFieldShouldReturn
中使用 [textField resignFirstResponder];
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:
Objective-C
[self.view endEditing:YES];
斯威夫特:
self.view.endEditing(true)
将 [self.view endEditing:YES];
放在您想要关闭键盘的位置(按钮事件、触摸事件等).
Put [self.view endEditing:YES];
where you would like to dismiss the keyboard (Button event, Touch event, etc.).
这篇关于按下回车键时如何以编程方式关闭键盘iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按下回车键时如何以编程方式关闭键盘iOS
基础教程推荐
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01