在Swift中按回车键切换文本字段

9 浏览
0 Comments

在Swift中按回车键切换文本字段

我正在设计一个iOS应用程序,当我在iPhone上按下回车键时,希望可以将光标定位到下一个文本框。

我找到了一些类似的问题,并且都有很好的答案,但它们都是Objective-C,我正在寻找Swift代码,目前我只有这些:

func textFieldShouldReturn(emaillabel: UITextField) -> Bool{
    return true
}

它被放置在与包含文本框的UIView连接和控制器相关的文件中,但我不确定那是否是正确的位置。

好吧,我尝试了一下,结果出现了这个错误:

//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.
}

admin 更改状态以发布 2023年5月24日
0
0 Comments

Swift 5

在键盘上点击“Return”键时,您可以轻松切换到另一个TextField。

  • 首先,您的视图控制器需要符合UITextFieldDelegate并在ViewController中添加textFieldShouldReturn(_:)委托方法。
  • Interface Builder中,从TextField拖动到ViewController。然后选择delegate选项。注意:对于所有TextField都要如此进行操作。
  • 创建所有TextFieldsIBOutlet

    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
      }
    }
    

0
0 Comments

确保你的UITextField的代理已经设置并且标签正确增加。这也可以通过界面建立器实现。

这是我找到的一个Objective-C的帖子链接:如何通过文本框导航(下一步/完成按钮)

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
   }
}

0