在窗口中切换自定义视图

时间:2012-06-21 01:57:31

标签: objective-c macos cocoa

我有一个.xib,它有一个带NSToolbar的窗口,并且有多个自定义视图,它们都是同一个xib的一部分。当我单击工具栏图标时,它会切换视图,但不显示我在该视图上的任何按钮或其他对象。

我知道视图正在切换,因为我对两个视图都有不同的大小,窗口正在调整

切换视图的代码:

NSInteger tag = [sender tag];

NSView *view = [self viewForTag:tag];
NSView *previousView = [self viewForTag: currentViewTag];
currentViewTag = tag;
NSRect newFrame = [self newFrameForNewContentView:view];

[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.1];

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];

1 个答案:

答案 0 :(得分:0)

这可能不是最好的方式,我不确定,但我切换视图的方式是这样的:

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    self.firstSubView = [[FirstViewController alloc]initWithNibName:@"FirstViewController" bundle:nil];
    self.secondSubView = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];

    [self.customView addSubview: self.firstSubView.view];
    self.firstSubView.view.frame = self.customView.bounds;

    self.firstViewIsSelected = YES;
}

- (IBAction)viewSwitched:(id)sender {
    if (self.firstViewIsSelected) {
        [self.firstSubView.view removeFromSuperview];
        [self.customView addSubview: self.secondSubView.view];
        self.secondSubView.view.frame = self.customView.bounds;
    }
    else{
        [self.secondSubView.view removeFromSuperview];
        [self.customView addSubview: self.firstSubView.view];
        self.firstSubView.view.frame = self.customView.bounds;
    }
    self.firstViewIsSelected = !self.firstViewIsSelected;
}