我正在设计一个iOS应用程序,我希望在iPhone中按回车键时,它可以将我定向到下一个下一个文本字段。
我发现了几个类似的问题,并且都给出了很好的答案,但是它们都恰好在Objective-C中,并且我正在寻找Swift代码,现在这是我到目前为止的想法:
func textFieldShouldReturn(emaillabel: UITextField) -> Bool{ return true }
它放置在连接的文件和包含文本字段的UIView的控制器中,但是我不确定那是否是正确的位置。
我基本上是Swift的新手,所以请解释每个小步骤,否则我会设法弄乱它。如果有任何区别,我也会使用最新版本的Xcode。
好的,所以我尝试了一下并得到了这个错误: //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. }
在此先感谢朋友!
确保UITextField已设置代表,并且标记已正确递增。这也可以通过界面生成器来完成。
UITextField
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 } }