UITextField不会返回,文本字段也无法更改。我该如何解决?

时间:2015-01-14 10:58:14

标签: ios xcode uitextfield uitextfielddelegate

我在尝试让键盘转到下一个字段时遇到问题,或者在按下返回键时返回,我的代码是:

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (weak, nonatomic) IBOutlet UITextField *userField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (strong, nonatomic) UITextField *textField;
@end

@implementation LoginViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}

- (void)viewDidLayoutSubviews
{
    [self.userField becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)tapLogin:(id)sender {

    NSLog(@"login");
}


#pragma mark - UITextFieldDelegate methods

// for return and next
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
if (textField == self.userField) {

    [self.passwordField becomeFirstResponder];
}
else if (textField == self.passwordField) {

    [self tapLogin:nil];
}
return YES;
}

游标出现在userField中,但点击返回键什么也没做,如果我手动点击另一个字段,即密码一,这也不会做任何事情。光标停留在用户名字段中。我已在头文件中实现了协议,并在接口构建器中将文本字段设置为委托。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

试试这个,

[self.userField becomeFirstResponder];删除viewDidLayoutSubviews方法,即删除以下方法

- (void)viewDidLayoutSubviews
{
    [self.userField becomeFirstResponder];
}

并添加

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self.userField becomeFirstResponder];
}