Created
March 9, 2021 16:37
-
-
Save bruzkovsky/62a669e460c8bc9b7770767e8742d992 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NumericEntryAccessoryViewEffect : PlatformEffect | |
{ | |
protected override void OnAttached() | |
{ | |
if (!(Element is Entry entry)) return; | |
entry.PropertyChanged += EntryOnPropertyChanged; | |
UpdateDoneButton(); | |
} | |
private void EntryOnPropertyChanged(object sender, PropertyChangedEventArgs e) | |
{ | |
if (e.PropertyName == nameof(Entry.Keyboard)) UpdateDoneButton(); | |
} | |
private void UpdateDoneButton() | |
{ | |
if (!(Element is Entry entry)) return; | |
if (entry.Keyboard == Keyboard.Numeric) AddInputAccessoryView(); | |
else RemoveDoneButton(); | |
} | |
private void RemoveDoneButton() | |
{ | |
if (!(Control is UITextField textField)) return; | |
textField.InputAccessoryView = null; | |
} | |
private void AddInputAccessoryView() | |
{ | |
if (!(Control is UITextField textField)) return; | |
if (!(Element is Entry entry)) return; | |
var toolbar = new UIToolbar(new RectangleF(0.0f, 0.0f, 50.0f, 44.0f)); | |
var minusButton = new UIBarButtonItem("+/-", UIBarButtonItemStyle.Plain, delegate | |
{ | |
entry.Text = entry.Text is {} text && text.StartsWith("-") | |
? entry.Text.Substring(1) | |
: $"-{entry.Text}"; | |
}); | |
var doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, delegate | |
{ | |
if (!textField.ResignFirstResponder()) | |
// if resign was unsuccessful, force it | |
textField.EndEditing(true); | |
((IEntryController) Element).SendCompleted(); | |
}); | |
toolbar.Items = new[] | |
{ | |
minusButton, | |
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), | |
doneButton | |
}; | |
textField.InputAccessoryView = toolbar; | |
} | |
protected override void OnDetached() | |
{ | |
if (!(Element is Entry entry)) return; | |
entry.PropertyChanged -= EntryOnPropertyChanged; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@RayCheung0616 good to hear that :-)