Skip to content

Instantly share code, notes, and snippets.

@bruzkovsky
Created March 9, 2021 16:37
Show Gist options
  • Save bruzkovsky/62a669e460c8bc9b7770767e8742d992 to your computer and use it in GitHub Desktop.
Save bruzkovsky/62a669e460c8bc9b7770767e8742d992 to your computer and use it in GitHub Desktop.
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;
}
}
@bruzkovsky
Copy link
Author

This is the platform specific (iOS) implementation of the Effect. You can put it anywhere in your .iOS project. If you use PCL/netstandard, then you‘ll need a RoutingEffect and use ResolutionGroupName and ExportEffect attributes, as described in the docs link above.

@RayCheung0616
Copy link

Thank you help, now I can use you NumericEntryAccessoryViewEffect.cs in iOS

@bruzkovsky
Copy link
Author

@RayCheung0616 good to hear that :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment