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

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


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

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;

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;

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);

Need Your Help

IE9 and Python issues?

python windows debugging internet-explorer-9 pipeline

Trying to debug a website in IE9. I am running it via Python.

How to organize time-based events for aggregation (such as visits) in a database?

ruby-on-rails database-design

I have a need to give my users time-based statistics about different kinds of visitors to their pages, such as how many visitors in the last week / last month / overall, and perhaps where those vis...