I'm currently trying to rebuild an existing project in a purely programmatic way (without storyboard and nib files). I know that there are already some posts in it, but they did not help me. This is the way to solve this problem:
main.swift
import Cocoa let delegate = AppDelegate() NS Application.shared().delegate = delegate let ret = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)`
AppDelegate.swift
import Cocoa class AppDelegate: NSObject, NSApplicationDelegate { let viewController = ViewController() let window = NSWindow(contentRect: NSMakeRect(0, 0, NSScreen.main()!.frame.size.width, NSScreen.main()!.frame.size.height), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: NSBackingStoreType.buffered, defer: false) func applicationDidFinishLaunching(_ aNotification: Notification) { viewController.view = NSView(NSMakeRect(0, 0, window.frame.size.width, window.frame.size.height)) viewController.view.wantsLayer = true window.contentView!.addSubview(viewController.view) window.makeKeyAndOrderFront(nil) } }
ViewController.swift
import Cocoa class ViewController: NSViewController { override func viewDidAppear() { let button = NSButton(frame: NSRect(x: 150, y: 200, width: 300, height: 30)) button.action = #selector(ViewController.buttonPressed(_:)) button.target = self view.addSubview(button) } func buttonPressed(_: Any?) { print("OK") } }
Later, the plan is to switch through these buttons between different view controllers and show different views. Is this right, or is there a βbetterβ way to do this? My goal is to have one window and different ViewControllers. Thank you for your help.
source share