3

I want the user to be able to enter no more than some number characters in a UITextView. This needs to work with copy-paste as well. I found this solution but it's Objective C and it has a drawback of resetting cursor position after the limit is reached.

What I'd like to have is a class that inherits from UITextView, exposes MaxCharacters property and does all the work inside.

Community
  • 1
  • 1
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511

1 Answers1

5

This code is based on manicaesar's answer but doesn't reset caret position after the limit is reached.

[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 (); }
}
Community
  • 1
  • 1
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511