1

I'm trying to set the the prompt to the beginning of some text in a UITextField based on this accepted answer Getting and Setting Cursor Position of UITextField and UITextView in Swift

However the prompt is getting set at the end, not the beginning. Has something changed in iOS10/Swift 3 to invalidate the code in the answer in that question?

        @IBOutlet weak var mdnTextField: UITextField!

        mdnTextField.text = "Some text"
        mdnTextField.tintColor = UIColor.textFieldPromptLightGray()
        mdnTextField.textColor = UIColor.textFieldPromptLightGray()
        let promptPosition = mdnTextField.beginningOfDocument
        mdnTextField.selectedTextRange = mdnTextField.textRange(from: promptPosition, to: promptPosition)
Community
  • 1
  • 1
Gruntcakes
  • 37,738
  • 44
  • 184
  • 378
  • I think much will depend on exactly when you are running that code. Can you revise your question to show some context? You haven't given enough code to allow me to experiment on my own. – matt Sep 20 '16 at 15:59
  • Thats in viewDidLoad, I've discovered that with this code then afterwards calling if let selectedRange = mdnTextField.selectedTextRange doesn't evaluate hence the selectedTextRange isn't getting set. – Gruntcakes Sep 20 '16 at 16:03
  • The cause is because mdnTextField.beginningOfDocument is uninitialized (so is endOfDocument for that matter), even though mdnTextField.text is being set to something. – Gruntcakes Sep 20 '16 at 16:15

1 Answers1

1

Move the promptPosition stuff to your text field's delegate's didBeginEditing.

matt
  • 515,959
  • 87
  • 875
  • 1,141