【问题标题】:How to limit UITextView character limit in MonoTouch? [duplicate]如何限制 MonoTouch 中的 UITextView 字符限制? [复制]
【发布时间】:2012-12-13 08:41:19
【问题描述】:

我希望用户能够在UITextView 中输入不超过一些数字字符。这也需要与复制粘贴一起使用。我找到了this solution,但它是Objective C,它的缺点是在达到限制后重置光标位置。

我想要的是一个继承自 UITextView 的类,公开 MaxCharacters 属性并在内部完成所有工作。

【问题讨论】:

    标签: c# xamarin.ios uitextview xamarin


    【解决方案1】:

    此代码基于manicaesar's answer,但在达到限制后不会重置插入符号位置。

    [Register ("LimitedTextView")]
    public class LimitedTextView : UITextView
    {
        public int MaxCharacters { get; set; }
    
        void Initialize ()
        {
            MaxCharacters = 140;
            ShouldChangeText = ShouldLimit;
        }
    
        static bool ShouldLimit (UITextView view, NSRange range, string text)
        {
            var textView = (LimitedTextView)view;
            var limit = textView.MaxCharacters;
    
            int newLength = (view.Text.Length - range.Length) + text.Length;
            if (newLength <= limit)
                return true;
    
            // This will clip pasted text to include as many characters as possible
            // See https://stackoverflow.com/a/5897912/458193
    
            var emptySpace = Math.Max (0, limit - (view.Text.Length - range.Length));
            var beforeCaret = view.Text.Substring (0, range.Location) + text.Substring (0, emptySpace);
            var afterCaret = view.Text.Substring (range.Location + range.Length);
    
            view.Text = beforeCaret + afterCaret;
            view.SelectedRange = new NSRange (beforeCaret.Length, 0);
    
            return false;
        }
    
        public LimitedTextView (IntPtr handle) : base (handle) { Initialize (); }
        public LimitedTextView (RectangleF frame) : base (frame) { Initialize (); }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-20
      • 2011-01-30
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多