如何将焦点设置到 iOS 文本字段? [英] How to set focus to an iOS text field?

查看:28
本文介绍了如何将焦点设置到 iOS 文本字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式将焦点设置到 iOS 中的某些 UITextField 上?

How do you programmatically set focus to some UITextField in iOS?

当您点击文本字段时,键盘会弹出以开始编辑文本字段.

When you tap on a textfield, the keyboard pops up to begin editing the textfield.

如何在不要求用户点击文本字段的情况下将焦点放在文本字段上并调出键盘?

How can you give focus to a textfield and bring up the keyboard without requiring the user to tap on the textfield?

推荐答案

使 textField 成为第一响应者;这也会弹出键盘:

Make the textField the first responder; this will also popup the keyboard:

[self.textField becomeFirstResponder];


还有一些更典型的示例代码,可能会对某人有所帮助,


And just some more typical example code which may help someone,

在您的故事板中,单击文本字段之一,并将 outlet-delegate 设置为相关类.在那个类中,在 .h 文件中确保你声明它是一个 UITextFieldDelegate

in your storyboard, click on one of the text fields, and set the outlets-delegate to be the class in question. In that class, in the .h file make sure that you declare that it is a UITextFieldDelegate

@interface Login : UIViewController <UITextFieldDelegate>

然后在 .m 文件中,你可以有这个......

Then in the .m file, you could have this for example...

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ( textField == self.loginEmail ) { [self.loginPassword becomeFirstResponder]; }
    if ( textField == self.loginPassword ) { [self yourLoginRoutine]; return YES; }
    return YES;
}

当用户点击下一步"时虚拟键盘上的按钮 - 在电子邮件"字段上 - 它将正确地将您移动到密码字段.当用户点击下一步"时虚拟键盘上的按钮 - 在密码"字段上 - 它会正确调用您的登录程序.

When a user clicks the "Next" button on the virtual keyboard - on the 'email' field - it will correctly move you to the password field. When a user clicks the "Next" button on the virtual keyboard - on the 'password' field - it will correctly call your yourLoginRoutine.

(在情节提要上的属性检查器上,请注意您可以在 Return 键上选择所需的文本……这里的Next"可以很好地处理电子邮件字段,而Done"可以很好地处理密码字段.)

(On the storyboard, on the attributes inspector, notice that you can select the text you want on the Return key ... here "Next" would work nicely on the email field and "Done" would work nicely on the password field.)

这篇关于如何将焦点设置到 iOS 文本字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆