實現效果: 當界面有兩個textField時, 利用return鍵切換光標位置.假如光標當前在第一個textField中, 在點擊return鍵時, 將光標自動定位到第二個textField
代碼示例:
#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```