Ryan Lehman
Ryan Lehman

Reputation: 7

How to add a permanent placeholder in a UItextfield for swift?

I am trying to allow a textfield to always have "@gmail.com" at the end when the user starts typing. So after any changes to the textfield it will always have that line attached to whatever the user has already typed and the user should not be able to delete it.

I have tried using "shouldChangeCharactersIn" function but can't seem to make it work.

The reason why I am doing this is so the user can understand that we only will accept gmail accounts and thought it would be the best way instead of trying to parse out the last 10 characters of the string to check for "@gmail.com".

Upvotes: 0

Views: 995

Answers (1)

Rashwan L
Rashwan L

Reputation: 38833

You should do it like this instead:

enter image description here

And have a control if the user adds @ then reject that part:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.tag == 0 {
        if string == "@" {
            return false
        }
    }
    return true
}

So you basically show the label that it´s @gmail.com and the user adds the first part in the textField.

Update:
And if you really want it inside the textField use this:

func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.text = textField.text! + "@gmail.com"

        textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.beginningOfDocument)
    }

Two parts here:
1: textField.text = textField.text! + "@gmail.com" - adds @gmail.com to your string

2: textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.beginningOfDocument) - places the cursor in the beginning when the user taps the textField.

Upvotes: 1

Related Questions