在NSWindow中更改视图会删除视图内容

时间:2012-10-04 02:38:54

标签: cocoa nsview nswindow nswindowcontroller nstoolbar

我正在使用NSToolbar和NSWindowController来更改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

1 个答案:

答案 0 :(得分:0)

我尝试了你的代码,我看到的并不是视图消失了,而是他们被错误定位并移出视野。我通过关闭IB中的自动布局来修复此问题,并在尺寸检查器中取消选择所有支柱和弹簧。我还取消选择了窗口的“可恢复”属性,这样如果您关闭了视图2可见的程序,并重新打开,则窗口(内部视图1)将是视图1的正确大小。