OSX Cocoa Swift: ViewController programming programmatically (without storyboard or nib files)

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.

+5
source share
1 answer

You also need to set target to the button. action indicates which method to call, but without purpose, it has nothing to call the method.

You may also need to change the action method to enable the sender : func buttonPressed(_: Any?) {...} parameter and set the action to #selector(ViewController.buttonPressed(_:)) .

I also noticed that your view controller is only held in a local variable in applicationDidFinishLaunching . It must be a property of AppDelegate , so there is a link to it, otherwise it will be deleted immediately.

+2
source

Source: https://habr.com/ru/post/1263923/


All Articles