MonoTouch.Dialog: How to set limit of number of ch

2019-03-30 19:56发布

问题:

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

回答1:

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



回答2:

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;


回答3:

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


回答4:

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