swift - 如何在 NSApplicationDelegate 上加载 NSViewController

标签 swift macos appdelegate

我正在尝试在我的 appDelegate 类上加载 ViewController。像这样:

class AppDelegate: NSObject, NSApplicationDelegate {

  @IBOutlet weak var window: NSWindow!

  var viewController = HomeViewController()

  func applicationDidFinishLaunching(aNotification: NSNotification) {
     self.window.backgroundColor = NSColor(rgba: "#02303A")
     self.viewController.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.window.frame), CGRectGetHeight(self.window.frame))
     self.window.contentView?.addSubview(self.viewController.view)
  }

}

我的 View Controller 非常简单,只是:

import PureLayout

class HomeViewController : NSViewController {

  let search : NSSearchField = {
    let search = NSSearchField.newAutoLayoutView()
    return search
  }()

  override func loadView() {
    super.loadView()
    self.view.layer?.backgroundColor = NSColor.blackColor().CGColor
    self.view.addSubview(search)
  }

}

但是当我编译项目时,日志返回:

Error

具有完整源代码的存储库:Github

有人知道是什么吗?我在我的 iOS 项目上这样做,效果很好。

最佳答案

  1. 您的 View Controller 没有 xib 文件,因此第一步是为 View 添加新文件:

enter image description here

  • 在新创建的 xib 文件中,选择文件所有者占位符,然后在检查器中将其自定义类设置为您的 View Controller 子类:
  • enter image description here

  • 最后,将 View Controller (文件所有者)的 View 导出连接到自定义 View 对象。
  • enter image description here

    (在此 View 中为 View Controller 构建用户界面,而不是在主 Nib 中构建用户界面。)

    关于swift - 如何在 NSApplicationDelegate 上加载 NSViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373070/

    相关文章:

    ios - 当应用程序被杀死 iOS 10 时处理通知操作

    macos - 为什么 NSDictionary 的 allKeys 和 allValues 方法返回 NSArray 而不是 NSSet?

    macos - Nginx + PHP-FPM 在 Mountain Lion 上非常慢

    xcode - 如何知道应用程序是否首次在 Mac 上运行

    ios - 无法从 AppDelegate 调用 ViewController 方法

    ios - 关闭然后打开 iOS 应用程序到特定的 ViewController

    swift - 可能通过枚举案例失败但仍使用其关联值?

    swift - 使用 AVCaptureVideoDataOutput 正确录制视频

    regex - 如何使用正则表达式替换最后一个单词?

    ios - 如何在 didRegisterForRemoteNotificationsWithDeviceToken 以外的方法中使用设备 token ?