Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 344
iLemming Avatar asked Dec 28 '22 10:12

iLemming


2 Answers

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

like image 192
poupou Avatar answered Dec 30 '22 00:12

poupou


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;
like image 24
Anuj Avatar answered Dec 29 '22 22:12

Anuj