簡體   English   中英

無法在.xib中設置NSTextView中的文本

[英]Can't set text in NSTextView from .xib

下面是一個簡單的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

我相信你是“編輯文本視圖后面的文本存儲”。 請參閱NSTextStorage的-edited:range:changeInLength: documentation。 這里的文檔有點模糊,但我相信-setString:在您請求的-mutableString上沒有通知文本存儲本身的更改(它只會在修改時更新屬性運行等)。

Call -edited:range:changeInLength:或者使用NSTextView的-setString:方法,如Mike C.推薦的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM