Last active
August 29, 2015 14:14
-
-
Save geirsagberg/aec53838136aba1d6631 to your computer and use it in GitHub Desktop.
FocusTextBinding for iOS
This file contains 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
// Based on http://stackoverflow.com/a/19221385/500976 | |
// In Setup.cs: | |
// protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry) | |
// { | |
// base.FillTargetFactories(registry); | |
// registry.RegisterCustomBindingFactory("FocusText", (UITextField textField) => new FocusTextBinding(textField)); | |
// } | |
using System; | |
using Cirrious.MvvmCross.Binding; | |
using Cirrious.MvvmCross.Binding.Bindings.Target; | |
using UIKit; | |
public class FocusTextBinding : MvxTargetBinding | |
{ | |
private bool _subscribed; | |
protected UITextField TextField | |
{ | |
get { return Target as UITextField; } | |
} | |
public override Type TargetType | |
{ | |
get { return typeof (string); } | |
} | |
public override MvxBindingMode DefaultMode | |
{ | |
get { return MvxBindingMode.TwoWay; } | |
} | |
public FocusTextBinding(object target) | |
: base(target) | |
{ | |
} | |
public override void SetValue(object value) | |
{ | |
if (TextField == null) return; | |
value = value ?? string.Empty; | |
TextField.Text = value.ToString(); | |
} | |
public override void SubscribeToEvents() | |
{ | |
if (TextField == null) return; | |
TextField.EditingDidEnd += HandleLostFocus; | |
_subscribed = true; | |
} | |
private void HandleLostFocus(object sender, EventArgs e) | |
{ | |
if (TextField == null) return; | |
FireValueChanged(TextField.Text); | |
} | |
protected override void Dispose(bool isDisposing) | |
{ | |
base.Dispose(isDisposing); | |
if (!isDisposing) return; | |
if (TextField != null && _subscribed) { | |
TextField.EditingDidEnd -= HandleLostFocus; | |
_subscribed = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment