3

我希望用户能够在UITextView. 这也需要与复制粘贴一起使用。我找到了这个解决方案,但它是 Objective C,它有一个缺点,即在达到限制后重置光标位置。

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

4

1 回答 1

5

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

[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 (); }
}
于 2012-12-28T01:29:24.037 回答