如何在MonoTouch中限制UITextView字符限制?

时间:2012-12-28 01:29:24

标签: c# xamarin.ios uitextview xamarin

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

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

1 个答案:

答案 0 :(得分:5)

此代码基于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 (); }
}