我找不到如何限制 EntryElement
的字符数。
我找不到如何限制 EntryElement
的字符数。
我也喜欢继承和事件机制 :-) 试试这个:
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;
}
}
请注意,还需要阅读Miguel的警告(编辑我的帖子):MonoTouch.Dialog:为EntryElement设置输入对齐方式
MonoTouch.Dialog 默认不包含此功能。最好的方法是复制并粘贴该元素的代码,然后将其重命名为 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);
};