c# iOS НЕ может позиционировать курсор в UITextField в позиции 1 - PullRequest
0 голосов
/ 05 августа 2020

Независимо от того, что я делаю, я НЕ могу установить курсор в позицию 1 в этой строке (___) ___-____ позиция 1 - это позиция, следующая сразу за открытием (. Я делаю это в методе EditingStarted делегата. В качестве руководства я следую коду здесь . в настоящее время мой код:

    public override void EditingStarted(UITextField textField)
    {
        if (MyParent.EditMask != "")
        {
            textField.Text = MyParent.EditMask.Replace("#", "_");
            // Set cursor position
            NSRange therange = new NSRange(index, 0);
            UITextPosition start = textField.GetPosition(textField.BeginningOfDocument, therange.Length - 1);
            UITextPosition end = textField.GetPosition(start, therange.Length);
            textField.SelectedTextRange = textField.GetTextRange(start, end);
        }
    }

Курсор ВСЕГДА появляется сразу после закрывающего ), ничего из того, что я делаю, не меняет. Понятия не имею почему. Я пробовал получить позицию первого подчеркивания:

int position = textField.Text.IndexOf("_");
NSRange therange = new NSRange(position, 0);

Но опять же, это приводит к тому, что курсор позиционируется сразу после закрытия ). Кто-нибудь видит, что я делаю неправильно?

**** Обновление ****

Просто, чтобы люди понимали контекст, приведенный выше код является частью класса с именем UIMaskedTextField, который Я создал для обработки всей моей маски / ввода текста в пользовательском интерфейсе. Этот класс:

class UIMaskedTextField : UITextField
{
    public string EditMask { get; set; }

    public UIMaskedTextField()
    {
        this.Delegate = new MaskTextViewDelegate(this);
    }

}
class MaskTextViewDelegate : UITextFieldDelegate
{
    private UIMaskedTextField MyParent;
    int index = 0;
    public MaskTextViewDelegate(UIMaskedTextField parent)
    {
        MyParent = parent;
    }

    public override void EditingStarted(UITextField textField)
    {
        if (MyParent.EditMask != "")
        {
            textField.Text = MyParent.EditMask.Replace("#", "_");
            // Set cursor position
            int position = textField.Text.IndexOf("_");

            NSRange therange = new NSRange(position, 0);
            UITextPosition start = textField.GetPosition(textField.BeginningOfDocument, therange.Location);
            UITextPosition end = textField.GetPosition(start, therange.Length);
            textField.SelectedTextRange = textField.GetTextRange(start, end);

        }
    }
    public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
    {
        int fieldlength = 10; // MyParent.EditMask.Length;
        string text = textField.Text;
        int NeedASpace = MyParent.EditMask.IndexOf(" ");
        string newText = "";
        if (text == "")
        {
            newText = MyParent.EditMask.Replace("#", "_");
        } else
        {
            newText = text;
        }

        string totalChar = newText.Replace(" ", "");
        totalChar = totalChar.Replace("(", "");
        totalChar = totalChar.Replace(")", "");
        totalChar = totalChar.Replace("-", "");
        totalChar = totalChar.Replace("_", "");

        int val;
        if ((totalChar + replacementString).Length <= fieldlength) {
            if (replacementString != "")
            {
                index = newText.IndexOf("_");
                StringBuilder sb = new StringBuilder(newText);
                char character = char.Parse(replacementString);
                sb[index] = character;
                newText = sb.ToString();


                textField.Text = newText;

                // Set cursor to next position, this works flawlessly
                NSRange therange = new NSRange(index, 0);
                UITextPosition start = textField.GetPosition(textField.BeginningOfDocument, therange.Location + 1);
                UITextPosition end = textField.GetPosition(start, therange.Length);
                textField.SelectedTextRange = textField.GetTextRange(start, end);

                newText = "";
            }
            else
            { // Still working the backspace key, so not done here yet.
                if (text.Length > 1)
                {
                    newText = text.Substring(0, text.Length - 1);
                }
                else
                {
                    newText = "";
                }
            }
        }

        return Int32.TryParse(newText, out val);
    }
}

Ответы [ 2 ]

1 голос
/ 06 августа 2020

Чтобы поместить курсор в UITextField в позицию 1:

public partial class ViewController : UIViewController
{
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    UITextField textfield1 { get; set; }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        // Perform any additional setup after loading the view, typically from a nib.

        var frame = new CGRect(10, 10, 300, 40);
        textfield1 = new UITextField(frame);

        textfield1.Text = "(___) ___-____";
        textfield1.Delegate = new myDelegate();

        View.Add(textfield1);


        textfield1.BecomeFirstResponder();

    }
}

public class myDelegate : UITextFieldDelegate {

    public override void EditingStarted(UITextField textField)
    {
        var arbitraryValue = 1;

        var newPosition = textField.GetPosition(textField.BeginningOfDocument, arbitraryValue);
        textField.SelectedTextRange = textField.GetTextRange(newPosition, newPosition);
    }
}

Обновить :

public override void DidChangeSelection(UITextField textField)
{
    var arbitraryValue = 1;

    var newPosition = textField.GetPosition(textField.BeginningOfDocument, arbitraryValue);
    textField.SelectedTextRange = textField.GetTextRange(newPosition, newPosition);

}
0 голосов
/ 12 августа 2020

Хорошо, наконец-то заработало. Решение @Jack Hua не сработает для меня, потому что я не могу установить текстовое поле как FirstResponder, потому что в режиме прокрутки есть несколько UIMaskedTextField, текстовые поля с масками не являются первыми под-представлениями в просмотре прокрутки , НО это дало мне некоторые идеи! Я начинал подозревать, что инициализация текстового поля при установке свойства text каким-то образом приводила к неправильному положению курсора, я считаю, что это именно то, что происходит, просто не могу это доказать, поскольку инициализация представления происходит за кулисами . НО Я подозреваю, что установка маски представления через свойство EditMask сделало инициализацию более быстрой и позволило установить позицию курсора. Это также устанавливает маску с самого начала, устраняя у пользователей любые сомнения относительно того, каким должен быть формат поля. Вот мой «последний» код:

class UIMaskedTextField : UITextField
{
    private string editmask = "";
    public String EditMask
    {
        get => editmask;
        set
        {
            if ((value != ""))
            {
                editmask = value;
                this.Text = editmask.Replace("#", "_"); ;
            }
        }
    }

    public UIMaskedTextField()
    {
        this.Delegate = new PhoneMaskTextViewDelegate(this);
    }
}

class PhoneMaskTextViewDelegate : UITextFieldDelegate
{
    private UIMaskedTextField MyParent;
    int index = 0;
    public PhoneMaskTextViewDelegate(UIMaskedTextField parent)
    {
        MyParent = parent;
    }

    public override void DidChangeSelection(UITextField textField)
    {
        // place the cursor in the first fill podition
        int y = textField.Text.IndexOf("_");

        if (y > -1)
        {
            var newPosition = textField.GetPosition(textField.BeginningOfDocument, y);
            textField.SelectedTextRange = textField.GetTextRange(newPosition, newPosition);
        }

    }
    public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
    {
        const string maskCharacters = "()-/ ";

        string newText = "";
        int val;

        if (replacementString != "")
        {
            int fieldlength = 10; // MyParent.EditMask.Length;
            string text = textField.Text;
            if (text == "")
            {
                newText = MyParent.EditMask.Replace("#", "_");
            }
            else
            {
                newText = text;
            }

            string totalChar = newText.Replace(" ", "");
            totalChar = totalChar.Replace("(", "");
            totalChar = totalChar.Replace(")", "");
            totalChar = totalChar.Replace("-", "");
            totalChar = totalChar.Replace("_", "");

            if (Utils.IsNumeric(replacementString))
            {
                if ((totalChar + replacementString).Length <= fieldlength)
                {
                    if (replacementString != "")
                    {
                        index = newText.IndexOf("_");
                        if (index > -1)
                        {
                            StringBuilder sb = new StringBuilder(newText);
                            char character = char.Parse(replacementString);
                            sb[index] = character;
                            newText = sb.ToString();


                            textField.Text = newText;

                            // Set cursor to next position
                            NSRange therange = new NSRange(index, 0);
                            UITextPosition start = textField.GetPosition(textField.BeginningOfDocument, therange.Location + 1);
                            UITextPosition end = textField.GetPosition(start, therange.Length);
                            textField.SelectedTextRange = textField.GetTextRange(start, end);
                        }
                        newText = "";
                    }
                }
            }
        } else
        { // Backspace/Delete pressed

            UITextRange position = textField.SelectedTextRange;
            string x = position.ToString();
            int positionofcursor = Convert.ToInt32(x.Substring(x.IndexOf("(") + 1, x.IndexOf(",") - x.IndexOf("(") - 1));

            string characterInPosition = "";


            // make sure we're not deleting a mask character
            do {
                positionofcursor -= 1;
                if (positionofcursor > -1)
                {
                    characterInPosition = textField.Text.Substring(positionofcursor, 1);
                    int j = maskCharacters.IndexOf(characterInPosition);
                }else
                {
                    break;
                }
            } while (maskCharacters.IndexOf(characterInPosition) > -1);

            if (positionofcursor > -1)
            {
                StringBuilder sb = new StringBuilder(textField.Text);
                sb[positionofcursor] = char.Parse("_");
                textField.Text = sb.ToString();

                NSRange therange = new NSRange(positionofcursor, 0);
                UITextPosition start = textField.GetPosition(textField.BeginningOfDocument, therange.Location);
                UITextPosition end = textField.GetPosition(start, therange.Length);
                textField.SelectedTextRange = textField.GetTextRange(start, end);
            }
        }

        return Int32.TryParse(newText, out val);
    }
}
...