I have a NSTextView
and i have a custom NSFormatter
that limits the string length. But how do i "[_textView setFormatter:customFormatter]
" on a NSTextView
? I can't find how to do that.
Example code would be appreciated!
Asked
Active
Viewed 1,021 times
0

Pedro Vieira
- 3,330
- 3
- 41
- 76
1 Answers
1
It's not possible to use a custom NSFormatter with a NSTextView. (That appears to be the province of NSControl, of which NSTextField is a subclass.)
However, it is possible to set up a delegate for your text view's text storage (NSTextStorage
), and implement -textStorageWillProcessEditing:
(a method of NSTextStorageDelegate
) ; this is where you could constrain your user's input. Your existing code for your custom NSFormatter might be adapted for use there.

Extra Savoir-Faire
- 6,026
- 4
- 29
- 47
-
Thank you, but i have a question: on the NSFormatter i used this code http://pastebin.com/NYFc5AnN to make the max length 256. How can i achieve the same with `-textStorageWillProcessEditing:`? – Pedro Vieira Oct 16 '12 at 18:15
-
@PedroVieira You could get the length of the text in the text storage (which is a subclass of `NSMutableAttributedString` - pass the `length` message to it), and act accordingly. – Extra Savoir-Faire Oct 16 '12 at 18:17
-
could u give me a quick example, please? i'm not achieving what i wanted. – Pedro Vieira Oct 16 '12 at 18:32
-
@PedroVieira Is the delegate method I suggested for you to implement being called? You should be receiving it whenever the user edits the contents of the text view. When it is called, you need to compare the length of the text in the text view's text storage against 256, and if it is greater than that, you need to adjust the storage so that it that length, maximum. I can lead you to the well, but you're going to have to fetch your own bucket of water, so to speak. – Extra Savoir-Faire Oct 16 '12 at 18:47
-
yes, it's being called when i type something and i'm comparing against the 256. but how do adjust the storage length? – Pedro Vieira Oct 16 '12 at 18:49
-
@PedroVieira I'm going to take a guess and assume that you want the latest 256 characters. So once you're inside your delegate method, pass the message `-[deleteCharactersInRange:NSMakeRange(0, n)]` to your text storage, where `n` is the number of characters over 256 that you need to remove. The `0` indicates that you're removing the characters from the beginning of the storage. This deletion should be reflected in the content of the text view. – Extra Savoir-Faire Oct 16 '12 at 19:06