【发布时间】:2012-01-09 00:46:04
【问题描述】:
我找不到如何限制EntryElement 上的字符数
【问题讨论】:
标签: c# .net ios xamarin.ios monotouch.dialog
我找不到如何限制EntryElement 上的字符数
【问题讨论】:
标签: c# .net ios xamarin.ios monotouch.dialog
我也更喜欢继承和事件 :-) 试试这个:
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: Setting Entry Alignment for 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);
};
【讨论】: