How to connect IBOutlet and IBAction in Swift language ?

Step 1. Create new project and select Cocoa Application Template.

-> Template automatically create the AppDelegate.swift , MainMenu.xib files and other stuff.

Step 2. Select the MainMenu.xib and open it. And then drag and drop the NSButton and NSTextField from the object library.

Step 3. Create IBOutlet and IBAction for NSTextField and NSButton respectively:-

-> Select the AppDelegate.swift file and open it. You will find two methods in this file such as:

func applicationDidFinishLaunching(aNotification: NSNotification?)
func applicationWillTerminate(aNotification: NSNotification?)

-> Add the following line of code for creating IBOutlet for NSTextField.

@IBOutlet var nameTxt : NSTextField

-> Add the following line of code for creating IBAction for NSButton.

@IBAction func sayHello(AnyObject)
{
var name :String = nameTxt.stringValue
var alert : NSAlert = NSAlert();
alert.informativeText = name;
alert.messageText = “Message”;
alert.runModal();
}

In above IBAction , showing the alert with name information getting from name text field with default “Ok” button.

Step 4. Connect IBOutlet and IBAction with NSTextField and NSButton respectively:-
-> Connecting outlets and action is similar to connecting outlets and action in objective-c.
-> Just right click on textfield and then choose new referencing outlet and drag over app delegate and then attach it.
-> Just right right click on button and then choose selector and drag over app delegate and then attach it.

Step 5. Run the application and give some input in textfield and then press button , you will see dialog with information passed in textfield.

Written By: Yogesh Arora, Software Engineer, Mindfire Solutions
Advertisements

About yogesha2014

Currently, i am working in MindfireSolution as cocoa application developer. I have 2+ year of experience in mac desktop application development. Also have knowledge about VC++ win32, MFC and MonoDevelop GTK#2.0.

Posted on October 31, 2014, in Cocoa Application, Cooca, Swift and tagged , , , , . Bookmark the permalink. Comments Off on How to connect IBOutlet and IBAction in Swift language ?.

Comments are closed.

%d bloggers like this: