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



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

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

但是NSTextView中的文本是不变的。

我想我有适当的出口myTextView连接。也许使用replaceTextContainer不是一个正确的方式来连接myTextView到textContainer?

悲哀的注意:我30年的c++编程没有顺利过渡到Obj-C/Cocoa使…

@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

我相信你是在"编辑文本视图背后的文本存储"。参见NSTextStorage的-edited:range:changeInLength:文档。文档在这里有点模糊,但我相信-setString:在-mutableString上,你所请求的不会通知文本存储本身的变化(它只更新属性运行等修改时)。

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

最新更新