I have been looking for solutions and found the following piece of code. But I do not know how to use it, unfortunately.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 25) ? NO : YES;
}
Just for testing purposes I set up an IBACTION
-(IBAction)checkIfCorrectLength:(id)sender{
[self textView:myTextView shouldChangeTextInRange: ?? replacementText: ?? ];
}
What do I pass for shouldChangeTextInRange
and replacementText
?
Or am I getting it completely wrong ?
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).
The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.
Swift – String Length/Count To get the length of a String in Swift, use count property of the string. count property is an integer value representing the number of characters in this string.
Calling textView:shouldChangeTextInRange:replacementText:
from checkIfCorrectLength:
doesn't make sense. If you want to test the length from multiple methods, factor the test out into its own method:
- (BOOL)isAcceptableTextLength:(NSUInteger)length {
return length <= 25;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)string {
return [self isAcceptableTextLength:textField.text.length + string.length - range.length];
}
-(IBAction)checkIfCorrectLength:(id)sender{
if (![self isAcceptableTextLength:self.textField.text.length]) {
// do something to make text shorter
}
}
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