How to go to next textField

I am currently building a UI that is a static grouped tableView and will probably end up having more than 40 rows with textLabels/TextFields.

In order for me to go from the one to the next what will be the easiest way to code it?

Something like this, and go through each field? Doesn’t seem very efficient, especially when the field names are given more descriptive names.

func textFieldShouldReturn(textField: UITextField) -> Bool {
    if textField == self.field1 {
        self.field2.becomeFirstResponder()
    } else if textField == self.field2 {
        self.field3.becomeFirstResponder()
    } 
        //...so on and so forth....
    return true
}

You could use the tag property of your text fields. Number them from 1 to number-of-rows. Then use the following function to advance to the next field. You’ll need to deal with the last field - perhaps wrapping around to the 1st field? I’m not at my Mac, so the syntax may be little off, but it should give you an idea.

func textFieldShouldReturn(textField: UITextField) -> Bool {
    let tag = textField.tag + 1
    self.viewWithTag(tag).becomeFirstResponder()
    return true
}

Have fun!

1 Like

Thanks for that tip, I guess the down side of numbering them will be if a new field is added or rearranged that the tag properties will need to be done manually again in the story board. Or is there a way to set the tag property in code as well?

You can set the tag property in code.

myView.tag = xxx