UITextField成为第一响应者

时间:2023-01-02 18:54:51

@interface CSRegisterTwoViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *codeTextFiled;

@property (weak, nonatomic) IBOutlet UITextField *secretTextFiled;

@end

@implementation CSRegisterTwoViewController

- (void)viewDidLoad {

[super viewDidLoad];

//成为第一响应者

[_codeTextFiled becomeFirstResponder];

//设置代理

_codeTextFiled.delegate = self;

_secretTextFiled.delegate = self;

//设置tag值

_codeTextFiled.tag = 1000;

_secretTextFiled.tag = 1001;

}

#pragma UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

//获取当前控制器的第二个textField

UITextField *textf = [self.view viewWithTag:1001];

//判断当前选择的如果是第一个

if (textField.tag == 1000) {

//再按return键时, 指定第二个为第一响应者

[textf becomeFirstResponder];

}

//判断当前选择的是第二个, 则释放第一响应者

[textField resignFirstResponder];

return YES;

}

@end

这里还介绍一下切换键盘为数字键盘的方法,以及点击空白处取消第一响应者

@interface CSRegisterViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userTelTextFiled;

@end

@implementation CSRegisterViewController

- (void)viewDidLoad {

[super viewDidLoad];

//设置第一响应者

[_userTelTextFiled becomeFirstResponder];

//设置数字键盘

_userTelTextFiled.keyboardType = UIKeyboardTypeNumberPad;

}

//取消第一响应者

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

[self.view endEditing:YES];

//这里不知道为什么楼主测试的时候,取消第一响应者的时候view视图顶部出来了一片空白,于是重新设置了view的frame

//self.view.frame = CGRectMake(0, 0, kWindowW, kWindowH);

}