neX neX - 7 months ago 14
Swift Question

Detecting if a "space" has been typed in a UITextField, and moving to a next UITextField

I'm new to Swift and I'm implementing a small form into a solution. I have three UITextFields and I want to make it so that if I type in a word and then type the "spacebar", the cursor will move to the next UITextField (i.e. it will prevent you from typing more than one word into the field).

If I was to do this how would I go about it?

I thought I should overwrite the

textField(_:shouldChangeCharactersInRange:replacementString:)


method - is this correct?

Thank you!

Answer

Try this

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // Get your textFields text
    let str = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

    // Check if the last character is a space
    // If true then move to the next textfield
    if str.characters.last! == " "{
        print("SPACE!")
        textField2.becomeFirstResponder()
    }
    else{
        print(str.characters.last!)
    }

    return true
}
Comments