Forum Xamarin.iOS

Setting cursor position in UITextField?

Its should be really simple, but i cant understand... So, does anyone know how to make this happen?
I´ve looked at the monotouch samples and tried:

            var range = new NSRange(selectionStart, 1);
            NumberTextField.SelectedTextRange = IndexedRange.GetRange(range);

But this causes this exception at runtime:
Objective-C exception thrown. Name: NSInvalidArgumentException Reason: -[iOS_IndexedRange asRange]: unrecognized selector sent to instance 0x7d9bd690


  • rmaciasrmacias USBeta, University ✭✭✭✭✭

    You could do something like this. Say you have a text field, and you want to programmatically place the cursor right after the 3rd letter of the text field, the below code will do that. Change indexToSet to any number and it will place the cursor at that position. Just make sure you don't go beyond the number of characters. :)

    var indexToSet = 3; //set cursor after the 3rd letter
    var positionToSet = entryField.GetPosition(entryField.BeginningOfDocument, indexToSet);
    entryField.SelectedTextRange = entryField.GetTextRange(positionToSet, positionToSet);
  • Ruben,
    I tried you code but entryField.BeginningOfDocument is always null. I also tried to set the entryField.Selected property to true but even after that entryField.BeginningOfDocument is coming null. How to make it have a value.

  • NeelamNeelam USMember

    Did anyone get the solution?

  • powerdevpowerdev USMember
    edited November 2017

    I found a solution:

     public override void ViewDidAppear(bool animated)
                txtAgreement.ScrollRangeToVisible(new NSRange(0, 0));
                txtAgreement.SetContentOffset(new CGPoint(0, 0), false);
  • AndyShokalookAndyShokalook USUniversity ✭✭

    I had a similar issue... I was creating a formatter for date and phone numbers... The textchange would get called twice when adding in the special characters. So you may need to trap for that and then call the code to set the cursor again when it gets hit the second time.

Sign In or Register to comment.