2012-10-04 45 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的正确大小。