Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit characters in UITextView ?

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 ?

like image 485
the_critic Avatar asked Feb 04 '12 21:02

the_critic


People also ask

How do I limit the number of characters in UITextField or UITextView?

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).

How do I limit characters in textField?

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.

How do I get the length of a string in Swift?

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.


1 Answers

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
    }
}
like image 53
rob mayoff Avatar answered Nov 09 '22 17:11

rob mayoff