I would like to set a limit to the number of characters that can be entered into a UITextField in an iOS app to 25 characters.
According to this post, it could be done in Objective-C like this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 25) ? NO : YES;
}
How can I do this exact same thing in C# with Xamarin.iOS?
If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).
TINYTEXT is a string data type that can store up to to 255 characters. TEXT is a string data type that can store up to 65,535 characters. TEXT is commonly used for brief articles. LONGTEXT is a string data type with a maximum length of 4,294,967,295 characters.
Create textLimit method This is the first step in limiting the characters for a text field or a text view. We need to create a method that will limit the the number of characters based on the current character count and the additional/new text that will get appended to the current value of the text field or text view.
This is untested, but I believe it may work:
UITextField myField;
myField.ShouldChangeCharacters = (textField, range, replacementString) => {
var newLength = textField.Text.Length + replacementString.Length - range.Length;
return newLength <= 25;
};
After 2 days working with this issue, I found out the solution for it by myself. It's working with copy/paste case. Hope it will useful.
public static bool CheckTexfieldMaxLength (UITextField textField, NSRange range, string replacementString, int maxLength)
{
int maxLength = 10;
int newLength = (textField.Text.Length - (int)range.Length) + replacementString.Length;
if (newLength <= maxLength) {
return true;
} else {
if (range.Length == 0 && range.Location > 0 && replacementString.Length > 0 && textField.Text.Length >= maxLength)
return false;
int emptySpace = maxLength - (textField.Text.Length - (int)range.Length);
textField.Text = textField.Text.Substring (0, (int)range.Location)
+ replacementString.Substring (0, emptySpace)
+ textField.Text.Substring ((int)range.Location + (int)range.Length, emptySpace >= maxLength ? 0 : (maxLength - (int)range.Location - emptySpace));
return false;
}
}
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