Stephane Gasparini
Stephane Gasparini

Reputation: 501

Setting Cursor Position of UITextField not working (swift)

I went thru this post Getting and Setting Cursor Position of UITextField and UITextView in Swift and I'm getting issue is selecting text.

I follow examples in the referred post and I still don't see any result. I have created a basic SingleViewApplication with just a UITextField in it.

The Textfield is set to "foobar" in viewDidLoad

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
     textField.text = "foobar"   }

In @IBAction Editing Did Begin I try to select the whole text using the method described in this post, see below.

@IBAction func EDB(_ sender: UITextField) {
    let startPosition = textField.beginningOfDocument
    let endPosition = textField.endOfDocument
    textField.selectedTextRange = textField.textRange(from: startPosition, to: endPosition  )
}

That I hopped will select all the text in my textField.

It didn't.

I put two breakpoints to display the selected range of my textField on the line let startPosition.... and one the last line those breakpoints execute po textField.selectedTextRange! and continue.

it confirms that I effectively change the range of my textField

<_UITextKitTextRange: 0x7fa42bb0d140> (6, 0)F

<_UITextKitTextRange: 0x7fa42b922640> (0, 6)F

However there is no visible selection on the UI and the cursor stays at the end of my textField.

What am I missing to get the UI showing my selected range ?

Basically I want to preselect a specific range of text of my UItextField when the user enter in edition.

Upvotes: 2

Views: 3327

Answers (2)

Maksym Musiienko
Maksym Musiienko

Reputation: 1248

Try to wrap selecting range into another method and call it with delay. I don't know exactly about your case, but in few situations small delayed helped me.

Here is Swift 2 version:

@IBAction func EDB(sender: UITextField) {
    performSelector(#selector(selectRange), withObject: nil, afterDelay: 0.01)
}

@objc private func selectRange() {
    let startPosition = textField.beginningOfDocument
    let endPosition = textField.endOfDocument
    textField.selectedTextRange = textField.textRange(from: startPosition, to: endPosition)
}

Upvotes: 3

fzh
fzh

Reputation: 688

you can try this code in your button action function.

textfield.selectAll(textfield)

hope help you!

Upvotes: 0

Related Questions