【问题标题】:MonoTouch.Dialog: How to set limit of number of characters for EntryElementMonoTouch.Dialog:如何设置 EntryElement 的字符数限制
【发布时间】:2012-01-09 00:46:04
【问题描述】:

我找不到如何限制EntryElement 上的字符数

【问题讨论】:

    标签: c# .net ios xamarin.ios monotouch.dialog


    【解决方案1】:

    我也更喜欢继承和事件 :-) 试试这个:

    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

    【讨论】:

    • 很好,应该注意到 ShouldChangeCharacters 也作为委托属性公开:-)
    • 希望我们能早日明白这一点,它们都以更 .NET 的方式暴露出来 :-)
    • 增加了对CellKey的覆盖,否则在cell回收时会和其他的NyEntryElements混在一起。
    • 如何连接到上面自定义条目元素上的 ShouldChangeCharacters 事件?
    【解决方案2】:

    默认情况下,MonoTouch.Dialog 没有此功能。最好的办法是复制并粘贴该元素的代码并将其重命名为 LimitedEntryElement。然后实现您自己的 UITextField 版本(类似于 LimitedTextField),它会覆盖 ShouldChangeCharacters 字符方法。然后在“LimitedEntryElement”中更改:

    UITextField entry;
    

    类似于:

    LimitedTextField entry;
    

    【讨论】:

    • 这很头疼... 为什么 Miguel 和其他人没有选择基于事件的方法?一切都必须通过覆盖一些方法来完成......该死
    • 我同意,它并不完全干净。话虽如此,它实际上是 MonoTouch 中继承的 Apple 模式。我会为此提出增强请求,因为我几乎可以肯定我们不是唯一有这种担忧的两个人:-P
    • 好吧,Apple 模式很糟糕。难怪为什么这么多人使用单点触控
    【解决方案3】:

    我这样做:

    myTextView.ShouldChangeText += CheckTextViewLength;
    

    还有这个方法:

    private bool CheckTextViewLength (UITextView textView, NSRange range, string text)
    {
        return textView.Text.Length + text.Length - range.Length <= MAX_LENGTH;
    }
    

    【讨论】:

      【解决方案4】:

      我更喜欢下面这样,因为我只需要为每种情况指定字符数。在这个示例中,我确定了 12 个数字。

      this.edPhone.ShouldChangeCharacters = (UITextField t, NSRange range, string replacementText) => {
          int newLength = t.Text.Length + replacementText.Length - range.Length;
          return (newLength <= 12);
      };
      

      【讨论】:

        猜你喜欢
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多