Joshua
Joshua

Reputation: 15510

Giving an NSTextView some padding/a margin

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?

Upvotes: 15

Views: 10100

Answers (5)

Ely
Ely

Reputation: 9131

This is all it takes when using a NSTextView with plain text style :

textView.textContainerInset = NSSize(width: 15, height: 5)

Upvotes: -1

Abizern
Abizern

Reputation: 150615

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

Upvotes: 18

George
George

Reputation: 119

Just to add an update to this. iOS7 adds a property to UITextView called textContainerInset. Calling setTextContainerInset will create margins inside the TextView for the content.

Upvotes: 5

Peter Hosey
Peter Hosey

Reputation: 96333

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).

Upvotes: 4

Peter Hosey
Peter Hosey

Reputation: 96333

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.

Upvotes: 2

Related Questions