I am developing a sample application for OSX. I want a text area where a user can enter and edit text. I want the text area to grow as the number of characters increases and I want to make the text area scrollable and keep its height fixed after it grows beyond certain length. I am using NSTextField for this purpose. But I am unable to make it scrollable. Also I tried using scrollable NSTextView inside a scrollview for this purpose. The NSTextField isn't allowing me to set the font and font size through the Interface builder.
1 Answers
First, as you've identified, you need to calculate the height of the text. Apple has the instructions you need here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TextLayout/Tasks/StringHeight.html
Then you need to change the frame or constraints (if you're using auto layout) of the NSTextView to adjust the size up to a predefined maximum.
If I were you, I'd subclass NSTextView and then override keyDown: so that the size is recalculated whenever the text is changed. Yes, it may not be the most efficient solution - but you have power to spare, and it's a nice easy fix.
As for setting the font, you need to set the font on the textstorage - not on the view. This is how to do it:
[textview.textStorage setFont:[NSFont fontWithName:@"Helvetica" size:12]];
If this doesn't work for you, can you post the code that isn't working?