无法在.xib中设置NSTextView中的文本

时间:2013-05-01 23:40:19

标签: objective-c cocoa interface-builder

下面是一个简单的Obj-C / Cocoa“hello world”窗口,它是在Carbon应用程序中初始化的。 .xib包含一个NSWindow,它有一个包含NSButton / NSButtonCell的NSView和一个NSScrollView / NSTextView / NSScroller。

代码编译并链接,没有警告。窗口正确显示,包含两个对象(按钮和文本字段)。按下按钮确实转到buttonWasPressed,我在Xcode的调试器中没有收到关于错误选择器的错误。

但是NSTextView中的文本没有改变。

我认为我有连接myTextView的正确插座。也许使用replaceTextContainer不是将myTextView连接到textContainer的正确方法吗?

SAD注意:我30年的C ++编程并没有顺利过渡到Obj-C / Cocoa make ...

@implementation DictionaryWindowController

- (id)init {
    self = [super init];
    // This is actually a separate Cocoa window in a Carbon app -- I load it from the NIB upon command from a Carbon menu event...
    NSApplicationLoad();
    if (![NSBundle loadNibNamed:@"Cocoa Test Window.nib" owner:self]) {
        NSLog(@"failed to load nib");
    }

    if (self) {

        // textStorage is a NSTextStorage* in DictionaryWindowController (NSObject)
        textStorage = [[NSTextStorage alloc] initWithString:@""];

        NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
        [givenStorage addLayoutManager:layoutManager];
        [layoutManager autorelease];

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

        // Is this how to "connect" the myTextView (NSTextView) from the .nib to the textStorage/layoutManager/textContainer?
        [myTextView replaceTextContainer:textContainer];

        [myTextView setMaxSize:NSMakeSize(LargeNumberForText, LargeNumberForText)];
        [myTextView setSelectable:YES];
        [myTextView setEditable:YES];
        [myTextView setRichText:YES];
        [myTextView setImportsGraphics:YES];
        [myTextView setUsesFontPanel:YES];
        [myTextView setUsesRuler:YES];
        [myTextView setAllowsUndo:YES];

        // shouldn't I be able to set the string in the NSTextStorage instance and cause the NSTextView to change its text and redraw?
        [[textStorage mutableString] setString:@"Default text from initialization..."];

    }

    return self;
}



- (IBAction)buttonWasPressed:(id)sender {

    // Pressing the button DOES get to this point, but the NSTextView didn't change...
    [[textStorage mutableString] setString:@"After button press, this text should be the content of the NSTextView."];
}

@end

1 个答案:

答案 0 :(得分:2)

我相信你正在“编辑文本视图后面的文本存储”。请参阅NSTextStorage的-edited:range:changeInLength:文档。这里的文档有点模糊,但我相信-setString:在您请求的-mutableString上没有通知文本存储本身的更改(它只会在修改后更新属性运行等)。

调用-edited:range:changeInLength:或者使用NSTextView的-setString:方法作为Mike C.推荐。