lovechicken
lovechicken

Reputation: 63

How can I move the cursor to the beginning of a UITextField in Swift?

I have seen this question asked many times, but every answer seems to be written in objective c, which I do not know nor do I know how to convert to Swift.

I have a text field where I want a user to input a percentage. I have it so that when they start editing the text box, the placeholder text disappears and is replaced with a percentage sign.

I want this percentage sign to always remain at the end of the input. I can't seem to figure out how to move the cursor back to the beginning of the text box to achieve this.

Here's the code for my begin editing action (this includes another text box where the user inputs a dollar amount, but the dollar sign comes first so that's no big deal)

    @IBAction func textBoxBeginEditing(sender: UITextField) {
    // Dismiss keyboard if the main view is tapped
    tapRecognizer.addTarget(self, action: "didTapView")
    view.addGestureRecognizer(tapRecognizer)

    // If there's placeholder text, remove it and change text color to black
    if (sender.textColor == UIColor.lightGrayColor()) {
        sender.text = nil
        sender.textColor = UIColor.blackColor()
    }

    // Force the keyboard to be a number pad
    sender.keyboardType = UIKeyboardType.NumberPad

    // Set up symbols in text boxes
    if (sender == deductibleTextBox) {
        sender.text = "$"
    }
    if (sender == percentageTextBox) {
        sender.text = "%"

        // This part doesn't do anything... Need a solution
        let desiredPosition = sender.beginningOfDocument
        sender.selectedTextRange = sender.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)

    }
}

That last bit was all I got from the internet for help. This app I am creating has been quite the iOS learning curve, so I apologize if this is a dumb question.

Upvotes: 0

Views: 1083

Answers (1)

Abhinav Dobhal
Abhinav Dobhal

Reputation: 630

let newPosition = textView.beginningOfDocument

textView.selectedTextRange = textView.textRangeFromPosition(newPosition, toPosition: newPosition)

In this we are getting the beginning of the textview and then setting the selected both to the beginning.

Upvotes: 1

Related Questions