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

Posts

  • 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. :)

    entryField.BecomeFirstResponder();
    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 9

    I found a solution:

     public override void ViewDidAppear(bool animated)
            {
                base.ViewDidAppear(animated);
                txtAgreement.ScrollRangeToVisible(new NSRange(0, 0));
                txtAgreement.SetContentOffset(new CGPoint(0, 0), false);
            }
    
Sign In or Register to comment.