0

我正在使用 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
4

1 回答 1

0

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

于 2012-10-04T04:59:00.957 回答