MonoTouch.Dialog:如何设置EntryElement的字符数限制
我无法find如何限制EntryElement
上的字符EntryElement
我更喜欢inheritance和事件:-)试试这个:
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; } }
但也阅读米格尔的警告(编辑到我的文章)在这里: MonoTouch.Dialog:设置条目alignmentEntryElement
MonoTouch.Dialog默认没有此function。 最好的办法是复制并粘贴该元素的代码,并将其重命名为像LimitedEntryElement。 然后实现自己的版本的UITextField(类似于LimitedTextField),它覆盖了ShouldChangeCharacters字符方法。 然后在“LimitedEntryElement”中改变:
UITextField entry;
像这样的东西:
LimitedTextField entry;
我这样做:
myTextView.ShouldChangeText += CheckTextViewLength;
而这个方法:
private bool CheckTextViewLength (UITextView textView, NSRange range, string text) { return textView.Text.Length + text.Length - range.Length <= MAX_LENGTH; }
我更喜欢下面,因为我只需要指定每个案例的字符数。 在这个例子中,我解决了12个数字。
this.edPhone.ShouldChangeCharacters = (UITextField t, NSRange range, string replacementText) => { int newLength = t.Text.Length + replacementText.Length - range.Length; return (newLength <= 12); };