代码之家  ›  专栏  ›  技术社区  ›  Rory Zipher

Nib的等效故事板函数

  •  0
  • Rory Zipher  · 技术社区  · 8 年前

    目前,该代码的情节提要版本使用与两个视图控制器关联的应用程序委托。单击按钮时,前窗口会显示动画并翻转,显示另一个(后)窗口。实例化视图控制器的代码是:

    mainWindow = [NSApplication sharedApplication].windows[0];
    secondaryWindow = [[NSWindow alloc]init];
    [secondaryWindow setFrame:mainWindow.frame display:false];
    
    // the below is what I'm not sure of - how to reference nib instead of storyboard?
    
    NSStoryboard *mainStoryboard = [NSStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    NSViewController *vc = [mainStoryboard instantiateControllerWithIdentifier:@"BackViewController"];
    [secondaryWindow setContentViewController:vc];
    

    在上面的例子中,我不确定引用笔尖而不是故事板的正确方法。 The project I'm trying to convert is located here . 我真的希望有人能帮上忙,谢谢!

    1 回复  |  直到 8 年前
        1
  •  1
  •   Charles Srstka    8 年前

    这很容易做到。只要做一个 NSViewController 子类(或 NSWindowController 如果希望它控制整个窗口,则为两个视图中的每个视图创建子类。对于每个视图,覆盖 -init 并将其称为super的实现 -initWithNibName:bundle: 使用视图的nib文件的名称:

    @implementation MyViewController
    
    - (instancetype)init {
        self = [super initWithNibName:@"MyViewController" bundle:nil];
    
        if (self == nil) {
            return nil;
        }
    
        return self;
    }
    

    请注意,如果你需要一个足够新的macOS版本(我认为它是10.11和更高的版本,但我可能需要一个版本左右),你甚至不需要做这么多,因为 NSViewController 将自动查找与类同名的nib文件。

    无论如何,现在您应该能够实例化 MyViewController 并将其视图插入到视图层次结构中,并以与处理任何其他视图相同的方式对其进行操作:

    MyViewController *vc = [MyViewController new];
    
    [someSuperview addSubview:vc.view];
    

    如果你想改用windows,你可以制作一个 NSWindowController 子类而不是 NSViewController . NSWindowController 使用起来有点烦人,因为它的初始值设定项采用nib名称 方便 初始值设定项,而 指定的 初始值设定项只需要一个 NSWindow . 所以,如果你使用,比如说,Swift,你不能像我上面用的那样 NSViewController . 当然,Objective-C通常让你想做什么就做什么,所以你实际上 可以 只要给super打电话就可以了 -initWithWindowNibName:owner: ,我不会告诉任何人,眨眨眼,轻推。然而,从风格上来说,你可能 应该 -initWithWindow: 经过 nil ,然后覆盖 windowNibName owner :

    @implementation MyWindowController
    
    - (instancetype)init {
        self = [super initWithWindow:nil];
    
        if (self == nil) {
            return nil;
        }
    
        return self;
    }
    
    - (NSNibName)windowNibName {
        return @"MyWindowController";
    }
    
    - (id)owner {
        return self;
    }
    

    这应该会给你一个窗口控制器,你可以用它初始化 +new (或 +alloc -初始化 如果你愿意),那么就叫它 -window 属性并按正常方式操作窗口。