views:

218

answers:

3

How would I give a NSTextView some padding/a margin to the left? I know how you do it in a NSTextField (by subclassing NSTextFieldCell) but how do you do it in a NSTextView?

EDIT: A bit more info: 1. The Text View just has plain text no rich text and no other fancy stuff like a proper text editor (e.g Paragraph insets). 2. Is it possible to use setTextContainerInset: for this?

A: 

Create a mutable paragraph style (most probably by making a mutable copy of the default paragraph style, then set its head indent and first-line head indent to the left margin you want. Then, set this paragraph style as the value of the NSParagraphStyleAttributeName attribute for the entire contents of the view's text storage.

Note that this will show up in RTF and possibly HTML data obtained from/given to you by the view. If the view is not read-only (i.e., the user can edit the text and you will retrieve or receive that text from the view), then you should probably avoid this solution. If the user can show the ruler and edit the paragraph style themselves, then you should definitely avoid this solution.

Peter Hosey
A: 

The way TextEdit does it (when in Wrap to Page mode) is to put the text view inside of a larger view, and set that larger view as the document view of the scroll view. That's more work to set up, but won't leak presentation information (in the form of a specially-customized paragraph style) into the model (the text).

Peter Hosey
A: 

You could try subclassing NSTextView and override the textContainerOrigin.

Details here.

For example this subclass will give a top and bottom margin of 5 left of 20 and right of 10.

@implementation MyTextView

- (void)awakeFromNib {
    [super setTextContainerInset:NSMakeSize(15.0f, 5.0f)];
}


- (NSPoint)textContainerOrigin {
    NSPoint origin = [super textContainerOrigin];
    NSPoint newOrigin = NSMakePoint(origin.x + 5.0f, origin.y);
    return newOrigin;
}

@end
Abizern