How to limit characters in a UITextView?

I searched for solutions and found the following code snippet. 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; } 

For testing only, I configured IBACTION

 -(IBAction)checkIfCorrectLength:(id)sender{ [self textView:myTextView shouldChangeTextInRange: ?? replacementText: ?? ]; } 

What should I pass for shouldChangeTextInRange and replacementText ? Or am I completely mistaken?

+6
source share
5 answers

Calling textView:shouldChangeTextInRange:replacementText: from checkIfCorrectLength: does not make sense. If you want to test the length of several methods, put the test in your 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 } } 
+11
source

Hi, I found and modified the code here. So, for xamarin users. try the following:

 textView.ShouldChangeText += delegate { if(textView.Text.Length > 159) // limit to one sms length { return false; } return true; } 
+2
source

You do not call this method yourself, the text view calls it whenever it is about to change its text. Just set the text view to the delegate property (for example, to your view controller) and implement the method there.

+1
source

If the current object is a text view delegate, you can use the following snippet:

 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { return weightTextView.text.length + text.length - range.length < 7; } 

It worked for me.

0
source
 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if([text length] == 0) { if([textView.text length] != 0) { return YES; } else { return NO; } } else if([[textView text] length] > your limit value ) { return NO; } return YES; } 
0
source

Source: https://habr.com/ru/post/907664/


All Articles