confused human
confused human

Reputation: 421

Cursor at the start of UITextField

A ViewController consist of two TextFields named textName & textEmail. View Controller loads with cursor on textName. textName contain pre populated word "@gmail.com".

On hitting keyboard's return Key from textName, focus is moved to Textfield textEmail. Here by default, cursor is placed after the word "@gmail.com"

I would like to get the cursor placed at the start. i.e. before @gmail.com

Here is my code. When i hit return key from textName, cursor goes to the beginning of textEmail. But when I tap on textEmail directly, cursor appears after the pre populated word. Please help me!

func textFieldShouldReturn(textField: UITextField) -> Bool {

        if textField == self.textName{
            textEmail.becomeFirstResponder()
            let desiredPosition = textEmail.beginningOfDocument
            textEmail.selectedTextRange = textEmail.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)
        }

        if textField == self.textEmail{


            dismissViewControllerAnimated(true, completion: nil)

        }

        return true
    }

As a note, I did try editing did begin action for textEmail and added below code but it didn't work either.

let desiredPosition = textEmail.beginningOfDocument
            textEmail.selectedTextRange = textEmail.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)

Upvotes: 1

Views: 958

Answers (2)

Mohit
Mohit

Reputation: 126

First tou set Delegate UITextFieldDelegate

After you TextField delegate set Self in viewDidLoad

Example

textName.delegate = self 
textEmail.delegate = self

then Copy this method in your viewController

 func textFieldShouldReturn(textField: UITextField) -> Bool
    {
        if textField == textName
        {
            textName.resignFirstResponder()
            textEmail.becomeFirstResponder()
             textEmail.text = "@gmail.com"
            let newPosition = textField.beginningOfDocument
           textEmail.selectedTextRange = textEmail.textRangeFromPosition(newPosition, toPosition: newPosition)



        }
        else if textField == textEmail
        {
            textEmail.resignFirstResponder()
        }
        return true
    }

Upvotes: 0

Rashwan L
Rashwan L

Reputation: 38833

Try this instead:

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == self.textName{
        let beginning = textField.beginningOfDocument
        textField.selectedTextRange = textField.textRange(from: beginning, to: beginning)
    }
}

So remove textEmail.becomeFirstResponder() and use textField.textRange instead of textEmail.textRangeFromPosition.

And inside of the textFieldDidBeginEditing function use the parameter textField as shown in my example above.

Upvotes: 3

Related Questions