3
votes

I need to position the cursor of a UITextField in the exact same position as another previous text field. I get the position of the cursor in the first text field as nint index = txtToField.GetOffsetFromPosition(txtToField.BeginningOfDocument, txtToField.SelectedTextRange.Start);, which correctly gets the number of characters from the beginning of the textfield my cursor is currently in. After some research, and using the question below:

Setting cursor position of UITextField

I have tried to implement the question's solution to setting the cursor position in a textfield, using the index I previously got. This doesn't work, and after making the text field the first responder and running:

txtTo.BecomeFirstResponder();
UITextPosition positionSet = txtTo.GetPosition(txtTo.BeginningOfDocument, position);
txtTo.SelectedTextRange = txtTo.GetTextRange(positionSet, positionSet);

It automatically puts your cursor at the end of the UITextField. Further, I attempted to check if the SelectedTextRange method worked as expected, however when trying to set all of the text in the text field as selected:

txtTo.BecomeFirstResponder();
txtTo.SelectedTextRange = txtTo.GetTextRange(txtTo.BeginningOfDocument, txtTo.EndOfDocument);

It also automatically puts the cursor to the end of the UITextField, which is a standard behaviour for BecomeFirstResponder(). Does SelectedTextRange not work in this current version of Xamarin?

I am using version 7.6.10 (build 27) of Xamarin and Xamarin.iOS version 12.0.0.15.

1

1 Answers

2
votes

Cause: The cursor is at the end of the text in dafault.When you init a UITextField and set it as FirstResponder in the method ViewDidLoad.The view is still not finish init.

Solution: You can call these method in the method EditingStarted .And don't forget set the delegate.

public partial clas xxxViewController:UIViewController,IUITextFieldDelegate

txtTo.WeakDelegate=this;

[Export("textFieldDidBeginEditing:")]
public void EditingStarted(UITextField textField)
{
  NSRange range = new NSRange(index, 0);
  UITextPosition start = textField.GetPosition(textField.BeginningOfDocument, range.Location);
  UITextPosition end = textField.GetPosition(start, range.Length);
  textField.SelectedTextRange = textField.GetTextRange(start, end);
} 

If you do want to call them in ViewDidLoad .You can set a delay (for example 0.1s).

//...
this.PerformSelector(new Selector("MoveCursorPosition:"),txtTo,0.1);
//...

[Export("MoveCursorPosition:")]
public void MoveCursorPosition(UITextField textField)
{
  NSRange range = new NSRange(index, 0);
  UITextPosition start = textField.GetPosition(textField.BeginningOfDocument, range.Location);
  UITextPosition end = textField.GetPosition(start, range.Length);
  textField.SelectedTextRange = textField.GetTextRange(start, end);
}