Set the maximum text size for NSTextView

77 views Asked by At

ALL,

All posts here on SO and Google points to a way of doing it for NSTextField. I need it for a NSTextView.

I am developing cross-platform application where I will need an NSTextView, not a Field, whose data will go into the DB field whose size is limited to 255 characters.

So I would rather prevent the user of the application to enter more than 255 characters, than unexpectedly cut the text o the DB insert.

I know the class don't have anythihg built-in, but maybe there is a way to make it work somehow.

TIA!!

EDIT:

I tried to implement the suggested method, but failed.

Here is what I did:

- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    [super shouldChangeTextInRange:range replacementText:text];
    // code to check the number of characters
}

I got following error/warning:

warning: instance method '-shouldChangeTextInRange:replacementText:' not found
      (return type defaults to 'id') [-Wobjc-method-access]
    [super shouldChangeTextInRange:range replacementText:text];
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/AppKit.framework/Headers/NSTextView.h:64:12: note: 
      receiver is instance of class declared here
@interface NSTextView : NSText <NSUserInterfaceValidations, NSTextInputClient, NSTextLayoutOrientationProvider, NSDraggingSource, NSText...
           ^
1 warning generated.

What am I doing wrong?

I do see that function in the NSTextView...

1

There are 1 answers

4
Willeke On

Copied from Limit number of characters in uitextview and adapted to NSTextViewDelegate, implement in the delegate of the text view:

- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRange:(NSRange)affectedCharRange 
    replacementString:(NSString *)replacementString {
    return textView.string.length + (replacementString.length - affectedCharRange.length) <= 140;   
}

The same trick in a subclass of NSTextView:

- (BOOL)shouldChangeTextInRange:(NSRange)affectedCharRange 
    replacementString:(NSString *)replacementString {
    return [super shouldChangeTextInRange:affectedCharRange replacementString:replacementString] &&
        (self.string.length + (replacementString.length - affectedCharRange.length) <= 140);    
}