例子如下:
首先.h文件继承UITextFieldDelegate 协议
#import <UIKit/UIKit.h>
#import "MainViewController.h"
@interface LoginViewController : UIViewController<MainDelegate,<span style="color:#FF0000;">UITextFieldDelegate</span>>
@property (nonatomic,strong) id <MainDelegate>delegate;
@end
.m文件中为 textField 变量设置 delegate = self
#import "LoginViewController.h"
@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *password;
@end
@implementation LoginViewController
- (void)viewDidLoad {
[_password setSecureTextEntry:YES];
_username.delegate = self;
_password.delegate = self;
然后 实现 UITextFieldDelegate 中的三个方法
//开始编辑输入框的时候,软键盘出现,执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect frame = textField.frame;
int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
//将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
if(offset > 0)
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
//当用户按下return键或者按回车键,keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
//输入框编辑完成以后,将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}
搞定
番外篇
如何点击Return自动转到下个文本框
回到storyboard,右击账号文本框(nameTextField)弹出面板,按住Did End on Exit事件旁边的圆圈,然后拖曳到右侧.h文件的空白地方,此时会弹出一个对话框给方法命名。输入名称 (nameTextField_DidEndOnExit)后回车确定,便自动生成了该事件方法。
随后按照同样的做法,为密码文本框(passTextField)的Did End on Exit事件连接方法(passTextField_DidEndOnExit)。
来到.m文件,填写具体代码——
例:
- (IBAction)name_DidEndOnExit:(id)sender {
[self.password becomeFirstResponder];
}
//在最后一个textfield,点击return键 关闭keyboard
- (IBAction)pwd_DidEndOnExit:(id)sender {
[sender resignFirstResponder];
//下面这句代码目的:在最后一个textfield 点击return后 自动执行下面login button 的 action
[self.loginBtn sendActionsForControlEvents:UIControlEventTouchUpInside];
}
轻触背景隐藏软键盘
只能通过Return关闭软键盘太不灵活了,应该提供轻触背景隐藏软键盘的功能。
在storyboard,点击背景View,将它的Custom Class设置为UIControl,这样才会出现Touch Down事件。
右击背景View弹出面板,按住Touch Down事件旁边的圆圈,然后拖曳到右侧.h文件的空白地方建立该事件的处理方法。
来到.m文件,填写具体代码——
例:
- (IBAction)view_DidEndOnExit:(id)sender {
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}