iLemming
iLemming

Reputation: 36274

MonoTouch.Dialog: How to set limit of number of characters for EntryElement

I cannot find how to cap the number of characters on EntryElement

Upvotes: 4

Views: 2119

Answers (4)

Arthur Accioly
Arthur Accioly

Reputation: 809

I prefer like below because I just need to specify the number of characters for each case. In this sample I settled to 12 numbers.

this.edPhone.ShouldChangeCharacters = (UITextField t, NSRange range, string replacementText) => {
    int newLength = t.Text.Length + replacementText.Length - range.Length;
    return (newLength <= 12);
};

Upvotes: 0

daniherculano
daniherculano

Reputation: 383

I do this:

myTextView.ShouldChangeText += CheckTextViewLength;

And this method:

private bool CheckTextViewLength (UITextView textView, NSRange range, string text)
{
    return textView.Text.Length + text.Length - range.Length <= MAX_LENGTH;
}

Upvotes: 0

poupou
poupou

Reputation: 43553

I prefer inheritance and events too :-) Try this:

class MyEntryElement : EntryElement {

    public MyEntryElement (string c, string p, string v) : base (c, p, v)
    {
        MaxLength = -1;
    }

    public int MaxLength { get; set; }

    static NSString cellKey = new NSString ("MyEntryElement");      
    protected override NSString CellKey { 
        get { return cellKey; }
    }

    protected override UITextField CreateTextField (RectangleF frame)
    {
        UITextField tf = base.CreateTextField (frame);
        tf.ShouldChangeCharacters += delegate (UITextField textField, NSRange range, string replacementString) {
            if (MaxLength == -1)
                return true;

            return textField.Text.Length + replacementString.Length - range.Length <= MaxLength;
        };
        return tf;
    }
}

but also read Miguel's warning (edit to my post) here: MonoTouch.Dialog: Setting Entry Alignment for EntryElement

Upvotes: 9

Anuj
Anuj

Reputation: 3134

MonoTouch.Dialog does not have this feature baked in by default. Your best bet is to copy and paste the code for that element and rename it something like LimitedEntryElement. Then implement your own version of UITextField (something like LimitedTextField) which overrides the ShouldChangeCharacters characters method. And then in "LimitedEntryElement" change:

UITextField entry;

to something like:

LimitedTextField entry;

Upvotes: 1

Related Questions