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.
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 (); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With