UITextField第一响应者及代理方法

实现效果: 当界面有两个textField时, 利用return键切换光标位置.假如光标当前在第一个textField中, 在点击return键时, 将光标自动定位到第二个textField


第一响应者.png

代码示例:

#import "ViewController.h"

#第一步: 遵循代理协议(注释)
@interface ViewController ()<UITextFieldDelegate> 

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    UILabel * userLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 100, 40)];
    userLabel.text = @"用户名:";
    userLabel.layer.borderColor = [UIColor colorWithRed:0.833 green:0.853 blue:0.857 alpha:1.000].CGColor;
    userLabel.layer.borderWidth = 1;
    userLabel.layer.cornerRadius = 8;
    userLabel.layer.masksToBounds = YES;
    userLabel.backgroundColor = [UIColor colorWithRed:0.726 green:1.000 blue:0.707 alpha:0.741];
    userLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:userLabel];
    
    
    UILabel * passwordLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 150, 100,40)];
    passwordLabel.backgroundColor = [UIColor colorWithRed:0.726 green:1.000 blue:0.707 alpha:0.741];
    passwordLabel.textAlignment = NSTextAlignmentCenter;
    passwordLabel.text = @"密   码:";
    passwordLabel.layer.borderColor = [UIColor colorWithRed:0.833 green:0.853 blue:0.857 alpha:1.000].CGColor;
    passwordLabel.layer.borderWidth = 1;
    passwordLabel.layer.cornerRadius = 8;
    passwordLabel.layer.masksToBounds = YES;
    [self.view addSubview:passwordLabel];
    
    
    UITextField * userTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 50, 200, 40)];
    userTextField.backgroundColor = [UIColor colorWithRed:0.580 green:0.824 blue:0.529 alpha:1.000];
    userTextField.placeholder = @"请输入用户名:";
    [self.view addSubview:userTextField];
    userTextField.tag = 1000;
    
    
    UITextField * passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 150, 200, 40)];
    passwordTextField.backgroundColor = [UIColor colorWithRed:0.580 green:0.824 blue:0.529 alpha:1.000];
    passwordTextField.placeholder = @"请输入密码:";

    [self.view addSubview:passwordTextField];
    passwordTextField.tag = 1001;
    
   #第二步: 设置代理
    userTextField.delegate = self;
    passwordTextField.delegate = self;
}

#第三步: 实现代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    //获取当前控制器的第二个textField
    UITextField *textf = [self.view viewWithTag:1001];
    //判断当前选择的如果是第一个
    if (textField.tag == 1000) {
        //再按return键时, 指定第二个为第一响应者
        [textf becomeFirstResponder];
    }
    
    //判断当前选择的是第二个, 则释放第一响应者
    [textField resignFirstResponder];
    
    return YES;
}

@end```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容