2012-10-04 46 views
0

我正在使用NSToolbar和NSWindowController更改NSWindow的視圖。當選擇了工具欄項目時,該窗口的視圖已成功更改,並且窗口根據視圖大小更改其大小。在初始加載窗口時,視圖的內容按預期顯示。但是,一旦選擇了工具欄項目,新視圖的內容將不可見,並且當視圖切換回原始視圖時,它的內容也將不再可見。不知道是什麼造成這種情況,所以任何幫助將不勝感激。在NSWindow中更改視圖刪除視圖的內容

#import <Cocoa/Cocoa.h> 

@interface WindowController : NSWindowController { 
    IBOutlet NSView *firstView; 
    IBOutlet NSView *secondView; 

    int currentViewTag; 
} 

- (IBAction)switchView:(id)sender; 

@end 

#import "WindowController.h" 

@interface WindowController() 

@end 

@implementation WindowController 

- (id)init { 
    self = [super initWithWindowNibName:@"WindowController"]; 
    if (self) { 
    } 

    return self; 
} 

- (void)windowDidLoad { 
    [super windowDidLoad]; 
} 

- (NSRect)newFrameForNewContentView:(NSView*)view { 

    NSWindow *window = [self window]; 
    NSRect newFrameRect = [window frameRectForContentRect:[view frame]]; 
    NSRect oldFrameRect = [window frame]; 
    NSSize newSize = newFrameRect.size; 
    NSSize oldSize = oldFrameRect.size; 

    NSRect frame = [window frame]; 
    frame.size = newSize; 
    frame.origin.y -= (newSize.height - oldSize.height); 

    return frame; 
} 

- (NSView *)viewForTag:(int)tag { 

    NSView *view = nil; 
    switch (tag) { 
     case 0: 
      view = firstView; 
      break; 
     case 1: 
      view = secondView; 
      break; 
    } 

    return view; 
} 

- (BOOL)validateToolbarItem:(NSToolbarItem *)item { 
    if ([item tag] == currentViewTag) return NO; 
    else return YES; 
} 

- (void)awakeFromNib { 

    [[self window] setContentSize:[firstView frame].size]; 
    [[[self window] contentView] addSubview:firstView]; 
    [[[self window] contentView] setWantsLayer:YES]; 
} 

- (IBAction)switchView:(id)sender { 

    double tag = [sender tag]; 
    NSView *view = [self viewForTag:tag]; 
    NSView *previousView = [self viewForTag:currentViewTag]; 
    currentViewTag = tag; 

    NSRect newFrame = [self newFrameForNewContentView:view]; 


    [NSAnimationContext beginGrouping]; 

    if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask) 
     [[NSAnimationContext currentContext] setDuration:1.0]; 

    [[[[self window] contentView] animator] replaceSubview:previousView with:view]; 
    [[[self window] animator] setFrame:newFrame display:YES]; 

    [NSAnimationContext endGrouping]; 
} 

@end 

回答

0

我嘗試了你的代碼,我所看到的是不是觀點消失了,但他們錯誤地被定位和遷出的觀點。我通過關閉IB中的自動佈局來解決這個問題,並取消選擇尺寸檢查器中的所有支柱和彈簧。我也取消了窗口的「可恢復」屬性,因此如果關閉程序並將視圖2視爲可見並重新打開,窗口(視圖1內部)將是視圖1的正確大小。