Swift & Xcode Basics: Adding a reference to a control in Swift

So I have been developing for iOS using cheats for a really long time and now that Swift is in beta I am going to try and convert over to using that instead of Xamarin and Appcelerator. I will be creating a series of blog posts outlining the things I have learned. Most of what I am discussing will be related to a Microsoft Developer converting to an Apple world.

The first thing you need to do is click Show the assistant editor which is the icon in xcode that looks like a tuxedo.  This displays the view controller code next to the storyboard designer.Main_storyboard_and_1__bash

 

 

Next, you will right click the UI control (in this case, the label that reads “First View”) and drag into the code on the right and drop inside the class definition above the viewDidLoad method.  You will see a blue line while you are dragging.  If you do not see that and your control moves you did not right click.
Main_storyboard_and_1__bash2

 

 

When you release the right button xcode will display a small callout editor window.  This allows you to name the variable that will reference the UI control.  I named mine lblTitle in this example.
Insert_Connection_and_Main_storyboard

Now you will see a variable in your code.  You can use this variable to reference the control.Main_storyboard_—_Edited

To demonstrate using the variable I set the text property of the label control I referenced to the text “Title”.  As you can see, I put this code in the viewDidLoad method.

Main_storyboard_—_Edited2

If you run the code in the simulator you will see the text for that label does in fact change when the view is displayed.
iOS_Simulator_-_iPhone_5s_-_iPhone_5s___iOS_8_0__12A4345d_

This is a very basic example of how to reference a UI component and set a property with swift.

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *