ios 在 Swift 中按返回键在文本字段之间切换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31766896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Switching between Text fields on pressing return key in Swift
提问by lucas rodriguez
I'm designing an iOS app and I want that when the return key is pressed in my iPhone it directs me to the next following text field.
我正在设计一个 iOS 应用程序,我希望在我的 iPhone 中按下返回键时,它会将我定向到下一个文本字段。
I have found a couple of similar questions, with excellent answers around but they all just happen to be in Objective-C and I'm looking for Swift code, now this is what I have up until now:
我发现了几个类似的问题,周围有很好的答案,但它们都恰好在 Objective-C 中,我正在寻找 Swift 代码,现在这是我到目前为止所拥有的:
func textFieldShouldReturn(emaillabel: UITextField) -> Bool{
return true
}
It's placed in the file that's connected and controller to the UIView that contains the text fields, but I'm not sure if thats the right place.
它被放置在连接和控制器到包含文本字段的 UIView 的文件中,但我不确定那是否是正确的位置。
I'm basically new to Swift, so explain every little step or I'll manage to mess it up somehow. Also I'm using the latest version of Xcode if that makes any difference.
我基本上是 Swift 的新手,所以解释每一个小步骤,否则我会以某种方式把它搞砸。此外,如果有任何区别,我将使用最新版本的 Xcode。
Okay, so I tried this out and got this error://could not find an overload for '!=' that accepts the supplied arguments
好的,所以我尝试了这个并得到了这个错误://could not find an overload for '!=' that accepts the supplied arguments
func textFieldShouldReturn(textField: UITextField) -> Bool {
let nextTag: NSInteger = textField.tag + 1
// Try to find next responder
let nextResponder: UIResponder = textField.superview!.viewWithTag(nextTag)!
if (nextResponder != nil) {
// could not find an overload for '!=' that accepts the supplied arguments
// Found next responder, so set it.
nextResponder.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
}
return false // We do not want UITextField to insert line-breaks.
}
Thanks in advance pals!
提前感谢朋友们!
回答by Caleb
Make sure your UITextField
delegates are set and the tags are incremented properly. This can also be done through the Interface Builder.
确保您的UITextField
代表已设置并且标签正确递增。这也可以通过 Interface Builder 来完成。
Here's a link to an Obj-C post I found: How to navigate through textfields (Next / Done Buttons)
这是我找到的 Obj-C 帖子的链接:How to navigation through textfields (Next / Done Buttons)
class ViewController: UIViewController,UITextFieldDelegate {
// Link each UITextField (Not necessary if delegate and tag are set in Interface Builder)
@IBOutlet weak var someTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do the next two lines for each UITextField here or in the Interface Builder
someTextField.delegate = self
someTextField.tag = 0 //Increment accordingly
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Try to find next responder
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
}
// Do not add a line break
return false
}
}
回答by Vinoth Vino
Swift 5
斯威夫特 5
You can easily switch to another TextField when clicking return key in keyboard.
单击键盘中的返回键时,您可以轻松切换到另一个 TextField。
- First, Your view controller conforms to
UITextFieldDelegate
and add thetextFieldShouldReturn(_:)
delegate method in ViewController - Drag from TextFieldto ViewControllerin Interface Builder. Then select the
delegate
option. Note: Do this for all TextField Create an
IBOutlet
for all TextFieldsclass ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var txtFieldName: UITextField! @IBOutlet weak var txtFieldEmail: UITextField! @IBOutlet weak var txtFieldPassword: UITextField! func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == txtFieldName { textField.resignFirstResponder() txtFieldEmail.becomeFirstResponder() } else if textField == txtFieldEmail { textField.resignFirstResponder() txtFieldPassword.becomeFirstResponder() } else if textField == txtFieldPassword { textField.resignFirstResponder() } return true } }
- 首先,您的视图控制器符合
UITextFieldDelegate
并textFieldShouldReturn(_:)
在ViewController 中添加委托方法 - 在Interface Builder 中从TextField拖动到ViewController。然后选择选项。注意:对所有 TextField 执行此操作
delegate
IBOutlet
为所有TextField创建一个class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var txtFieldName: UITextField! @IBOutlet weak var txtFieldEmail: UITextField! @IBOutlet weak var txtFieldPassword: UITextField! func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == txtFieldName { textField.resignFirstResponder() txtFieldEmail.becomeFirstResponder() } else if textField == txtFieldEmail { textField.resignFirstResponder() txtFieldPassword.becomeFirstResponder() } else if textField == txtFieldPassword { textField.resignFirstResponder() } return true } }
回答by kubacizek
I suggest that you should use switch statement in textFieldShouldReturn(_:)
.
我建议你应该在textFieldShouldReturn(_:)
.
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case nameTextField:
phoneTextField.becomeFirstResponder()
case phoneTextField:
emailTextField.becomeFirstResponder()
case emailTextField:
descriptionTextField.becomeFirstResponder()
default:
textField.resignFirstResponder()
}
return false
}
回答by libec
This approach needs some changes in table views and collection views, but it's okay for simple forms I guess.
这种方法需要对表视图和集合视图进行一些更改,但我想对于简单的表单来说是可以的。
Connect your textFields
to one IBOutletCollection
, sort it by its y coordinate and in textFieldShouldReturn(_:)
just jump to the next textfield until you reach the end:
将您的连接textFields
到 one IBOutletCollection
,按其 y 坐标对其进行排序,然后textFieldShouldReturn(_:)
跳转到下一个文本字段,直到到达结尾:
@IBOutlet var textFields: [UITextField]!
...
textFields.sortInPlace { class ViewController: UIViewController,UITextFieldDelegate
.frame.origin.y < .frame.origin.y }
...
func textFieldShouldReturn(textField: UITextField) -> Bool {
if let currentIndex = textFields.indexOf(textField) where currentIndex < textFields.count-1 {
textFields[currentIndex+1].becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return true
}
Or just look at sample project(xcode 7 beta 4)
或者只是看看示例项目(xcode 7 beta 4)
回答by BHUVANESH MOHANKUMAR
I have tried many codes and finally this worked for me in Swift 3.0 Latest [March 2017]
我尝试了很多代码,最后这在Swift 3.0 最新版 [2017 年 3 月] 中对我有用
The "ViewController" class should inherited the "UITextFieldDelegate" for making this code working.
“ViewController”类应该继承“UITextFieldDelegate”以使此代码工作。
override func viewDidLoad() {
userNameTextField.delegate = self
userNameTextField.tag = 0
userNameTextField.returnKeyType = UIReturnKeyType.next
passwordTextField.delegate = self
passwordTextField.tag = 1
passwordTextField.returnKeyType = UIReturnKeyType.go
}
Add the Text field with the Proper Tag nuber and this tag number is used to take the control to appropriate text field based on incremental tag number assigned to it.
添加带有正确标签编号的文本字段,此标签编号用于根据分配给它的增量标签编号将控件带到适当的文本字段。
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
return true;
}
return false
}
In the above code, the "returnKeyType = UIReturnKeyType.next" where will make the Key pad return key to display as "Next" you also have other options as "Join/Go" etc, based on your application change the values.
在上面的代码中,“returnKeyType = UIReturnKeyType.next”将使键盘返回键显示为“Next”,您还有其他选项如“Join/Go”等,根据您的应用程序更改值。
This "textFieldShouldReturn" is a method of UITextFieldDelegate controlled and here we have next field selection based on the Tag value incrementation
这个“textFieldShouldReturn”是 UITextFieldDelegate 控制的一个方法,这里我们有基于 Tag 值增量的下一个字段选择
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let nextField = self.view.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
回答by coldembrace
Caleb'sversion in Swift 4.0
Caleb在Swift 4.0 中的版本
class MyViewController: UIViewController, UITextFieldDelegate {
let textFieldA = UITextField()
let textFieldB = UITextField()
let textFieldC = UITextField()
let textFieldD = UITextField()
var textFields: [UITextField] {
return [textFieldA, textFieldB, textFieldC, textFieldD]
}
override func viewDidLoad() {
// layout textfields somewhere
// then set delegate
textFields.forEach { override func viewDidLoad() {
super.viewDidLoad()
emailTextField.delegate = self
passwordTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailTextField {
passwordTextField.becomeFirstResponder()
}else {
passwordTextField.resignFirstResponder()
}
return true
}
.delegate = self }
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let selectedTextFieldIndex = textFields.firstIndex(of: textField), selectedTextFieldIndex < textFields.count - 1 {
textFields[selectedTextFieldIndex + 1].becomeFirstResponder()
} else {
textField.resignFirstResponder() // last textfield, dismiss keyboard directly
}
return true
}
}
P.S. textField.superview?
not working for me
PStextField.superview?
对我不起作用
回答by Tieda Wei
Swift & Programmatically
Swift & 以编程方式
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.returnKeyType == .next {
Email.resignFirstResponder()
Password.becomeFirstResponder()
} else if textField.returnKeyType == .go {
Password.resignFirstResponder()
self.Login_Action()
}
return true
}
回答by mazenqp
the easiest way to change to next text Field is this no need for long code
更改到下一个文本字段的最简单方法是不需要长代码
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let txtTag:Int = textField.tag
if let textFieldNxt = self.view.viewWithTag(txtTag+1) as? UITextField {
textFieldNxt.becomeFirstResponder()
}else{
textField.resignFirstResponder()
}
return true
}
回答by Parth Patel
回答by Lahiru Pinto
Swift 4.2
斯威夫特 4.2
This is a More Generic and EasiestSolution, you can use this code with any amount of TextFields. Just inherit UITextFieldDelegateand update the Textfield Tagaccording to the order and copy this function
这是一个更通用和最简单的解决方案,您可以将此代码与任意数量的 TextFields 一起使用。只需继承UITextFieldDelegate并根据顺序更新Textfield Tag并复制此函数
##代码##