UITextField Max Length in C# with Xamarin.iOS

This is untested, but I believe it may work:

UITextField myField;
myField.ShouldChangeCharacters = (textField, range, replacementString) => {
    var newLength = textField.Text.Length + replacementString.Length - range.Length;
    return newLength <= 25;
};

I ended up doing it with a delegate rather than lamba notation:

UITextField myField;
myField.ShouldChangeCharacters = new UITextFieldChange(delegate(UITextField textField, MonoTouch.Foundation.NSRange range, string replacementString) {
    int newLength = textField.Text.Length + replacementString.Length - range.Length;
    return newLength <= 25;
});

But I think that Rolf's way using lambda is easier to read.


After 2 days working with this issue, I found out the solution for it by myself. It's working with copy/paste case. Hope it will useful.

public static bool CheckTexfieldMaxLength (UITextField textField, NSRange range, string replacementString, int maxLength)
    {

        int maxLength = 10;
        int newLength = (textField.Text.Length - (int)range.Length) + replacementString.Length;
        if (newLength <= maxLength) {
            return true;
        } else {
            if (range.Length == 0 && range.Location > 0 && replacementString.Length > 0 && textField.Text.Length >= maxLength)
                return false;

            int emptySpace = maxLength - (textField.Text.Length - (int)range.Length);

            textField.Text = textField.Text.Substring (0, (int)range.Location)
            + replacementString.Substring (0, emptySpace)
            + textField.Text.Substring ((int)range.Location + (int)range.Length, emptySpace >= maxLength ? 0 : (maxLength - (int)range.Location - emptySpace));
            return false;
        }
    }