Search code examples
iosswiftuitextfield

Swift - Jump between textfields with one button


App

        @IBOutlet weak var umCent: UITextField!
        @IBOutlet weak var doisCent: UITextField!
        @IBOutlet weak var cincoCent: UITextField!
        @IBOutlet weak var dezCent: UITextField!
        @IBOutlet weak var vinteCent: UITextField!
        @IBOutlet weak var cinquentaCent: UITextField!
        @IBOutlet weak var umEuro: UITextField!
        @IBOutlet weak var doisEuro: UITextField!
        @IBOutlet weak var cincoEuro: UITextField!
        @IBOutlet weak var dezEuro: UITextField!
        @IBOutlet weak var vinteEuro: UITextField!
        @IBOutlet weak var cinquentaEuro: UITextField!
        @IBOutlet weak var cemEuro: UITextField!
        @IBOutlet weak var duzentosEuro: UITextField!
        @IBOutlet weak var quinhentosEuro: UITextField!

        @IBAction func proximo(_ sender: UIButton) {

        }

I want to jump between the 15 textFields when I press the "proximo" button, for example, if I have to edit the 0.01 and I want to edit the 0.02 I just need to press the button.


Solution

  • Create an outlet collection

    @IBOutlet weak var textFields: [UITextFields]!
    

    In Interface Builder (IB) add your text fields to the collection outlet in the appropriate order.

    @IBAction func proximo(_ sender: UIButton)
    {
        if let index = textFields.firstIndex { $0.isFirstResponder }
        {
            let nextIndex = (index + 1) % textFields.count // Wraps around back to index 0.
    
            textFields[nextIndex].becomeFirstResponder()
        }
        else
        {
            // Optional: Select first text field if none was selected (yet).
            textFields[0].becomeFirstResponder()
        }
    }