В моем приложении Xamarin.Forms у меня есть поведение, которое задает положение курсора (поведение действует как маска для нашего поля ввода).
CursorPosition устанавливается вызовом: targetEntry.CursorPosition = newCursorPosition. Это отлично работает на Android, но на iOS курсор всегда идет в конец текста, это ошибка конкретной версии iOS или это просто по всем направлениям?
Все остальное в поведении (обеспечение того, чтобы текст был правильно замаскирован, чтобы он правильно удалял символ подчеркивания, который действует как руководство для того, где пользователь должен вводить свои данные) работает так, как должно. Я могу опубликовать больше моего кода, если это необходимо
Обновлено: newCursorPosition - это статическая переменная типа int.
Редактировать 2: включая мой код
открытый класс DurationViewMaskBehavior: поведение { общедоступный статический экземпляр DurationViewMaskBehavior = new DurationViewMaskBehavior(); частный статический интервал курсораPosition = 0;
protected override void OnAttachedTo(BorderlessEntry entry) {
entry.TextChanged += OnInput;
base.OnAttachedTo(entry);
}
protected override void OnDetachingFrom(BorderlessEntry entry) {
entry.TextChanged -= OnInput;
base.OnDetachingFrom(entry);
}
/// <summary>
/// This method exists to ensure that if the user tried to shape the field to be something it shouldn't
/// that it will return the mask to the correct format; this is to ensure that we only have valid data and also that
/// </summary>
/// <param name = "text"></param>
/// <returns></returns>
private bool PatternMatchCheck(string text) {
var regex = @"^(([0-9]\d{1}|__|[0-9]_|[0-9]|[0-9]*__|[0-9]\d{1}_| *) Min, ([0-9]\d{1}|__|[0-9]_|[0-9]|[0-9]__|[0-9]\d{1}_|) Sec|((Min, Sec)|[0-9]+ Min, Sec|Min, [0-9]+ Sec))$";
var match = Regex.Match(text, regex, RegexOptions.IgnoreCase);
return match.Success;
}
private void OnInput(object sender, TextChangedEventArgs args) {
//Only fire this behavior when the user actually inputs some type of value
if (!string.IsNullOrWhiteSpace(args.NewTextValue)) {
var text = args.NewTextValue;
//How this works so far:
//At first you get the input, so text.length == 1 is fine. Then
//it updates itself, so really for every input this event fires twice.
//After that we will have to look at the actual text itself so we can use
//the index instead
var targetObject = ((BorderlessEntry)sender);
if (!PatternMatchCheck(args.NewTextValue) && args.OldTextValue.Length > 2) {
targetObject.Text = args.OldTextValue;
return;
}
if (text.Length == 1) {
targetObject.Text = $"{text}_ Min, __ Sec";
cursorPosition = 1;
}
if (text.Contains("_")) {
if (text.Length > 1 && (text[2] != '_' || text[1] != '_')) {
if (text[2] == '_' && text[0] != '_') {
targetObject.Text = $"{text.Substring(0, 2)} Min, __ Sec";
cursorPosition = 8;
}
}
if (text.Length > 1 && text[8] != '_' && text[9] == '_' && text[8] != ' ') {
targetObject.Text = $"{text.Substring(0, 2)} Min, {text[8]}_ Sec";
cursorPosition = 9;
}
if (text.Length > 1 && text[8] != '_' && text[9] != '_') {
targetObject.Text = $"{text.Substring(0, 2)} Min, {text.Substring(8, 2)} Sec";
cursorPosition = text.Length-1;
}
}
targetObject.CursorPosition = cursorPosition;
}
}
}
@ G.hakim Я опубликую больше об этом позже сегодня, когда у меня будет возможность, но похоже, что корень проблемы заключается в части кода, который у меня есть в моем вопросе, поскольку он должен устанавливать позицию





Выяснил, почему, похоже, что iOS требует, чтобы я привязал другое событие .TextChanged, которое обрабатывает настройку курсора. Это странно и отстало, но это работает.
private void SetCursor(object sender, TextChangedEventArgs args) {
((BorderlessEntry)sender).CursorPosition = cursorPosition;
}
if (isRegistered) {
targetObject.TextChanged -= SetCursor;
isRegistered = false;
}
else {
targetObject.TextChanged += SetCursor;
isRegistered = true;
}
Вы должны опубликовать свой код, иначе люди будут спекулировать, и у вас не будет правильного решения за один раз.