1
votes

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
NSTextField isn't supposed to be scrollable (as you've discovered). It's for one line only. NSTextView is the correct view for what you're trying to achieve. You don't say what NSTextView doesn't work for you though. Could you be more specific - and, perhaps, post some code so that we can see what you're doing?headbanger
@headbanger Basically I want the NSTextView to grow as the text increases but only until some height. After that I want to scroll. How can I achieve this? Is there anyway I can calculate the height required by the NSTextView at runtime?hcnimkar

1 Answers

0
votes

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?