Xcode way to print "Hello World" when button is clicked in OS X Swift application?
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).
- click on this view controller
- check the right panel and the 3rd icon on the top. Click it
- You will see "Custom Class" "Class" "Module"
- In "Class", drop down and choose the view controller class you implemented
- Make sure you implemented this buttonTap function in the class
- In the storyboard make sure you see the button
- hold the control key, click on the button and drag to the yellow cube
- release your mouse
- see the buttonTapped function show in the menu popping up
- 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.
You need to connect your button to your viewController also:
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 !!!"
}
}
Charlweed
Updated on July 18, 2020Comments
-
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 :)