5
votes

I'm can't seem to build a working NSTextView programmatically. Starting from a new project template I have this code (mostly coming from Apple's "Text System User Interface Layer Programming Guide"):

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSString *string = @"Here's to the ones who see things different.";
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:string];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [textStorage addLayoutManager:layoutManager];

    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(300, 300)];
    [layoutManager addTextContainer:textContainer];

    NSTextView *textView = [[NSTextView alloc] initWithFrame:NSMakeRect(50, 50, 300, 300)
                                               textContainer:textContainer];

    [textContainer setWidthTracksTextView:YES];
    [textView setVerticallyResizable:YES];
    [textView setHorizontallyResizable:NO];
    [textView setAutoresizingMask:NSViewWidthSizable];

    [[self.window contentView] addSubview:textView];
}

Running the app, a window opens with a white square in it that's supposed to be the NSTextView, but there's no text, and there's no way to interact with the text view. Moreover, I tried adding text to the text view in code after the view is created using [textView setString:@"Some string."], but that doesn't work either. (Incidentally, I've also tried putting it in a NSScrollView first, in case that somehow was the issue, but that didn't help.)

I can't for the life of me figure out what the problem is. What am I missing?

2
Usually NSTextView used together with NSScrollView. See example in this answer: stackoverflow.com/a/45947994/1418981Vlad

2 Answers

0
votes

This should work, although I tried it out myself and was unable to edit too. It could possibly be a bug now, but I'm not 100% sure. If you need to use the containers and layout managers just use the one that comes from the initWithFrame: method (without the text container).

NSTextView *textView = [[NSTextView alloc] initWithFrame:NSMakeRect(50, 50, 300, 300)];
NSLayoutManager *layoutManager = textView.layoutManager;
NSTextContainer *textContainer = textView.textContainer;
NSTextStorage *textStorage = textView.textStorage;

//Do your edits here
0
votes

To expand on TheAmateurProgrammer's answer:

If you need to use the containers and layout managers just use the one that comes from the initWithFrame: method (without the text container)

With iOS, needed to create the text storage, layout manager, and text container for UITextView to work as intended. For NSTextView to function, needed to not create those. Had same results as OP until this change--the view was located accurately, but didn't display text or show insertion point or invoke delegate methods--and then the text view worked properly.