跳过正文
  1. Posts/

How to generate a NSViewController without a Nib?

目录

In the last days, I created all the ViewControllers through the storyboard or the Nib (for views). Today, when I created a demo project without any Nib file, the ViewController did not show as I expected.

WTF, Can you believe that? I cannot even create a ViewController now.

There exist some differences between iOS and macOS.

iOS
#

In the previous development on the iOS platform, create a ViewController, specifically UIViewController instance, is dead simple as below.

import UIKit

class ViewController: UIViewController {}
let vc = ViewController()
print("vc.view.frame = \(vc.view.frame)")

You can create a UIViewController without a nib file, and customize the view’s properties as you like. Nothing unexpected happen and ViewController has a default view.

macOS (Cocoa)
#

However, when you want to create a NSViewController in the same way, something wrong occur.

import Cocoa

class ViewController: NSViewController {}
let viewController = ViewController()
print("vc.view.frame = \(vc.view.frame)")

It looks like the same as what we do for UIViewController. And it should work like UIViewController.

However, an exception is thrown, which shows that ‘could not load the nibName’. Why?

[General] -[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: Demo.ViewController in bundle (null).

So, It looks like that NSViewController will not create a default rootView for us. We must create one by ourselves. The key is the loadView. Just override the loadView() method, then create a NSView instance.

import Cocoa

class ViewController: NSViewController {
  override func loadView() {
    self.view = NSView()
  }
}

That’s it.

Now, I have found that macOS development has many differences with iOS. You may encounter many fundamental pitfalls, and when you indeed stumble, be patient. To read the Apple’s documentations is you top priority, then Google please.

References
#

  1. Instantiate a UIViewController without Nib
  2. Instantiate a NSViewController without Nib

相关文章

关于 Library 和 Framework

·8 分钟
Library 和 Framework 的概念大家应该脑海里都有一些,本文旨在讲述下基本概念,没有对每个字节都了如指掌。关于基本的编译过程在 Build Process 一文中也大概讲述了一些。

Build Process

编程语言的处理过程大致会有五个阶段,其每个阶段均有对应的工具: 预处理器 Preprocessor 编译器 Compiler 汇编器 Assembler 链接器 Linker 加载器 Loader 我们以一个简单的源文件,来看看具体这几个步骤都做了哪些事情。

Mac 平台上那些 Dockless 的 App 都是如何实现的?

Menu Only 算是 Cocoa App 中最常见的一项,它使得 App 不占用你的 Dock 栏,在多 workspace 的时候也不影响正常使用,随时都可以在屏幕的菜单栏中执行快捷操作。尤其是针对一些需要便捷性要求比较高的应用来讲,Menu bar 的功能必不可少。本文就简单介绍一下关于 Menu App 中关键的几个开发步骤。

为 NSView 增加 backgroundColor

·1 分钟
NSView 作为 Cocoa 中最基本的构成元素,是构成整个 Mac App 视图体系的基础,和 UIView 在 iOS 世界中的位置一样重要,可是在 UIView 里司空见惯的背景色设置,在 NSView 中却不见身影。