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

不想你离开。 提交于 2019-12-05 00:53:02

问题


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


来源:https://stackoverflow.com/questions/8314815/monotouch-dialog-how-to-set-limit-of-number-of-characters-for-entryelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!