Xcode way to print "Hello World" when button is clicked in OS X Swift application?

32,072

Solution 1

The way to link a button for OSX is the same for iOS

@IBAction func buttonTapped(button: NSButton)
{
   ...
} 

One thing to note is here we use NSButton.

In the storyboard, you should see a view controller (a yellow cube).

  1. click on this view controller
  2. check the right panel and the 3rd icon on the top. Click it
  3. You will see "Custom Class" "Class" "Module"
  4. In "Class", drop down and choose the view controller class you implemented
  5. Make sure you implemented this buttonTap function in the class
  6. In the storyboard make sure you see the button
  7. hold the control key, click on the button and drag to the yellow cube
  8. release your mouse
  9. see the buttonTapped function show in the menu popping up
  10. choose this function

Solution 2

You just need to add a label and a button to your window. Then you need to connect your label outlet to your code.

enter image description here

You need to connect your button to your viewController also:

enter image description here

import Cocoa

class ViewController: NSViewController {

    @IBOutlet var strLabel: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func printHello(sender: AnyObject) {
        strLabel.stringValue = "Hello World !!!"
    }

}
Share:
32,072
Charlweed
Author by

Charlweed

Updated on July 18, 2020

Comments

  • Charlweed
    Charlweed almost 4 years

    I'm an experienced Java and Visual Studio developer, but I am just starting out with Swift & Xcode. I am an utter noob, who has never written a line of objective-c. I want to print "Hello World" when I click on the button that I have added in the "Storyboard" view for my application. But I cannot figure out how to get Xcode to insert an event method anywhere in the swift source code files. I’ve read %60 of "The Swift Programming Language", but I don't know any of the cocoa apis yet. Most examples reference objective-c files that do not exist in a Swift application. I also am not using the iOS platform, so I suspect some examples I've pasted (i.e. @IBAction func buttonTapped ) fail because they are not applicable to OS X applications.

    I would appreciate a little help :)