Domenic
Domenic

Reputation: 11

Adding a ViewController to application without a storyboard

How do you implement functions like viewDidLoad() in an empty project without a storyboard?

Sorry for the beginner question. I have been searching for hours now but it still doesn't work. Thanks for any help!

edit:
I am using a .xib file, just no .storyboard. At the moment I'm setting everything up inside applicationDidFinishLaunching()

edit2:
I think I finally got it:
I created a new project without a storyboard, created a file ViewController.swift together with an ViewController.xib and added

window?.contentViewController = ViewController()

into the applicationDidFinishLaunching function inside the AppDelegate. I cannot believe I didn't get this sooner. Sorry BaseZen for your wasted time and thank you very much for trying to help me!

Upvotes: 1

Views: 908

Answers (1)

BaseZen
BaseZen

Reputation: 8718

The question is (far) too broad. Please make it more specific, perhaps tailoring it to the part of it that is answered here, just for the sake of others in the future.

There are in-code equivalents to all Storyboard techniques. Your google technique is:

MacOS Swift how to doXyz programmatically

By the way, iOS is probably 10x more popular in terms of search results. So if the platform doesn't matter and you just want to learn how to do it in code, start with iOS.

This will get you started with layout: https://www.hackingwithswift.com/read/6/3/auto-layout-in-code-addconstraints

For example, initializing a non-IBOutlet:

var myButton = NSButton()

Setting its text:

myButton.title = "Hello"

Adding it to a View Controller's view:

view.addSubview(myButton)

Constraining it within the view:

// You have to learn some verbose weird stuff to do this in code
myButton.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint( ... ))

Connecting it to a non-IBAction handler, assuming you have a function called func handleAction(sender: AnyObject)

myButton.target = self
myButton.action = #selector(MyViewController.handleAction(_:))

Simplest possible example:

import Cocoa

class ViewController: NSViewController {
    var b = NSButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        b.title = "Hi! I am a button"
        b.target = self
        b.frame = NSRect(x: 100, y: 100, width: 100, height: 25)
        b.action = #selector(ViewController.handleButtonPress(_:))
        view.addSubview(b)
    }

    func handleButtonPress(sender: NSButton) {
        b.title = "Thank you for clicking."
        b.sizeToFit()
    }
}

Upvotes: 1

Related Questions