How to make Cocoa NSTextView grow as a user types into it?

For the Cocoa application that I am writing, I would like to maintain a panel to the right of the main content of the document, where users can add notes for the currently selected content of the document. (If you are familiar with Microsoft Word or Scrivener, this function is similar to the comment function in these applications.) Scrivener does a good job of starting with a text field that matches the default text size and then grows higher than the user types in it. I would like to implement the same behavior for my Cocoa application.

What is the main strategy?

+6
source share
2 answers

There are delegate methods that allow you to capture the actual keystrokes when they enter.

Implement the delegate method below to cancel the first keyboard based responder

-(BOOL)textFieldShouldReturn:(UITextField *)textfield 

Implement the delegate method below to determine when the focus was returned to the TextField. You can also delete the current text or save the text that was already there if you want

 -(void)textFieldDidBeginEditing:(UITextField *)textfield 

Implement the delegation method below to detect the characters you enter and where (based on the caret position) and essentially add the characters to your private and displayed line (displayed in your text box)

 -(BOOL)textView:(NSTextView *)aTextView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString 

Implement the delegation method below to determine when editing is finished, so that you can perform any other cleanup, etc. that you want to do.

 -(void)textFieldDidEndEditing:(UITextField *)textField 

I will get back to you on the dynamic size of your TextView, but this (at least on iOS), as I saw, has a solution, and at some point I used it. You will essentially make your font size static, potentially static in width, and then edit the height depending on how many lines you have, or you can keep your height static and change your width based on characters, etc. .. to you.

Here's a great set of StackOverflow answers about dynamic scaling. How do I set up a UITextView for its contents?

So, if you combine keystroke recognition with dynamic size, you should have one.

0
source

Custom, not NSScrollView, the built-in NSTextView does the trick. See My answer here. How to make NSTextView grow with text? .

0
source

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


All Articles