SWIFT cheat sheet

I’ve added some swift codes which can be helpful for beginners. You can bookmark this page, as it can be used for quick recall.

Declare variables in swift:

Concatenate strings  in swift

Declare arrays in swift

Find number of elements in array in swift

Tuples in swift

Declare Class in swift

Instantiate class in swift

Declare Struct (or structure) in swift

Inherit Class in swift

Declare  simple method / function without argument and return type:

Declare method / function with argument and return type

For loop

For loop in another form

For loop in array

While loop:

 

 

 

 

How to add UITextField, UITextView and UILabel programmatically in swift 4.0

In iOS app development, sometime we need to add Textfields, textviews, labels etc programmatically. It gives you control over customizing styles, size and position of them. I’m going to place codes (swift Language) here so that you can get all of them from one place.
Following codes will work in any view controller
UITextField:
TextView:
Label:

 

How to add UIButton programmatically in SWIFT

In iOS app development sometime we’ve to create Buttons programmatically or dynamically. Today, I’ll show you how to do this using SWIFT programming language.

Let’s create a new Single View iOS application in Xcode. Name the project “DynamicButton”. Select swift as programming language.

Now go to ViewController.swift. In ViewDidLoad method we’ll write some codes that will add one button to the screen automatically at run time.

Let’s create a new method createButton and write some codes inside the method that will do the magic:

Explanation:

First we initialize a button object and keep it in button variable.

Then we set title and color of title of it.

In the following line of code, we add position and size of the button.

Add the button to view.

Finally let’s call the createButton in viewDidLoad method.

Now if you run the project (cmd + R) you can see a button created. If you tap on the button, nothing will happen at this moment. To call a method when button is pressed, we can write:

Do not forget to add ‘:’ after action method name (i.e. buttonPressed:). In action parameter of .addTarget, you set the method name that should be called. Now write buttonPressed method.

The buttonPressed: method simply displays an alert view. Now run the project and view result.

iOS Simulator Screen Shot Feb 18, 2015, 3.20.49 PM

The whole ViewController.swift will look like this:

 

Still feeling tired? Click here to download the project.

 

 

How to use Core-Data with SWIFT

Core data is a framework that is used to save data in iOS app development and OS X platform. Today we’ll develop an application using SWIFT programming language that will have a textfield, a button and a textview that will save and display data fetched from Core Data. To learn more about Core-Data please visit:

Introduction to Core Data Programming Guide

Summary:

Step 1: Create Project

Step 2: Design Core-Data database

Step 3: Write script to save and fetch data from core data.

 

Step 1:

1. Create a new project in Xcode. In first window of the wizard select Single view application. In next screen, select SWIFT from dropdown box and also check “Use Core Data” checkbox (bottom of the wizard). Please use “NotePad” as your project name.

Screen Shot 2015-02-12 at 11.56.09 PM

2. Open Main.storyboard and add a textfield, a button. Below the button add big textview. ( Note: textfield is for one line. For multiple lines use textview).

Screen Shot 2015-02-13 at 12.06.29 AM

 

Step 2:

1. Now, open NotePad.xcdatamodeld (YourProjectName.xcdatamodeld). This is the place where you design your database.

2. Here you add Entity (Entity is similar to Table of Oracle / MySql database, but not exactly). At the bottom of the page, you will see Add Entity button (1). Click on it. New entity (2) will be added. By double clicking on it, you can change it’s name. I changed it to “Note”

3. Now select the entity (if it’s not already selected). Add “Attribute” to it by clicking + button (3) below the Attributes section. Attribute is similar to column of a table. For each attribute we should select a type from dropdown box. I’m using only one attribute “paper” with type “String”.

4. At this point you have to do an important thing. In Utilities panel (Right side bar), you will see a box labeled: “Class” (4) in entity section. Write here : NotePad.Note; Actually, it should be ApplicationName.EntityName

5. Now we’ll generate Entity Classes. To do this, go to Editor > Create NSManagedObjectSubclass. Select the data model (It’s the file name that we have worked on). In next screen, select Entity name. We’ve only one Entity. Click next. Now, you will see a dialog box for saving entity file. Here, from language dropdown box select swift and finally click Create button.

coredata

Step 3:

1. Add outlets to textField and textview.

2. Add IBAction to button. You can also rename the button to “Add”

3. Open ViewController.swift.

We’ll edit this file. Before we proceed, let me give you an example. Suppose we have some food, one tray and a refrigerator. To save the food, we’ve to put it on the tray and keep the tray inside refrigerator. Saving method of Core data is similar. Here data is food, managedObject is tray and managedObject.save is equivalent to keeping tray contained food inside refrigerator.

Screen Shot 2015-02-16 at 9.45.25 PM

 

First import CoreData in your viewController

declare an array NSManagedObject below IBOutlet declaration. so the code will look like this:

 

To fetch data from CoreData we can use following method:

Above method fetches all data in Note entity. At the end of the method, we used for loop to get each text inside paper and add them in a local variable. finally show all texts in large text view.

To save data in Core data use following code. We are saving text in paper attribute (column) of Note entity (table)

 

Now implement saveNote in IBAction actionAddNote. Clear the text field so that you can add new note.

 

Full source code of ViewController.swift. You can also download the whole project from the link provided at the end this tutorial.

 

You can download the whole project by clicking here.

How to implement SOAP Web service with SWIFT 4.0 programming language?

Update (13 November, 2017): Updated codes for Xcode 9 and swift 4.0

Update (25 March, 2016): I’ve updated codes for Xcode 7 and swift 2.0

Update (16 September, 2016): Code updated for Xcode 7.2.1 and swift 2.1.1

Today I’ll show you how to develop SWIFT based application that communicates with a web service using SOAP.

We’ll use following  web service and convert temperature from celcious to fahrenheit:

http://www.webservicex.net/ConvertTemperature.asmx

If you are new to SOAP, then I’d recommend you to learn it from the following link:

http://www.w3schools.com/webservices/ws_soap_intro.asp

And to learn the basics of swift, you can read apple’s documentation by clicking here.

Requirements: Basic understanding of Web services, SOAP and swift.

First open Xcode 9 (or later version) and create a new project named “Temperature Converter”. Select swift as language from first dialog box. Created project will contain ViewController.swift, Main.storyboard and other files.

Screen Shot 2014-10-24 at 11.23.03 PM
Open Main.storyboard and add textfield, labels and a buttons as shown in the screenshot below.
Screen Shot 2014-10-24 at 11.30.28 PM
Add outlets of textfields and add an action for the button. If the image below is too small to view, please click on it to see the full size. In case if you don’t know how to do this, open storyboard and swift file side by side in Assistant editor view. Ctrl + Drag and drop textfields to the swift file. Do the same thing for action, just change the connection type from “Outlet” to “Action” in popup box. I gave the outlet names txtCelcius and txtFahrenheit. For button’s action name I used actionConvert. You can use any name. I didn’t add any outlet for button.
Screen Shot 2014-10-24 at 11.31.55 PM
Now let’s change the codes step by step to add SOAP service with this application.

Step 1: Add delegation names that we’ll be delegating through out this project. We’ll delegate:UITextFieldDelegate, NSURLConnectionDelegate, NSXMLParserDelegate.

 

Step 2: We need some variables to store received data from server and keep track of those data. Let’s declare them.

 

Step 3: Modify the actionConvert method to let it get user input from Celcius textfield and make a request to server using post method. The full actionConvert method will look like following code:

 


 

Step 4: Using following 3 methods we’ll delegate with NSURLConnection. First 2 methods will save data received from server in mutableData variable. The last method will start NSXMLparser to parse SOAP message.

 

Step 5: We need 2 methods to parse SOAP message returned from server. I’ll discuss one by one so that you can understand them.

The first method is called each time a new node or element of SOAP (or XML) is parsed. We need to  save this name so that we can detect each node in second method. Let’s see the first method:

 

 

The second method will check the current element name and if it finds “ConvertTempResult” element, then it displays the value in Fahrenheit text field.

Now, save and run the code. If you put any numeric value in Celsius box and tap Convert button, Fahrenheit box will display the result fetched from server.

 

iOS Simulator Screen Shot Oct 27, 2014, 7.33.25 PM

 

You can download the whole project from here.

Or can pull the latest project code from Github:

https://github.com/rubelbd82/soapwithswift

Best of luck!!!

How to customise UILabel using SWIFT 4.0?

Requirements:

Operating System: OS X 10.9.4+

IDE: Xcode 9

Level: Beginner to intermediate.

We can use Storyboard and interface builder to change the look and feel of UILabel. However, sometime, we have no other way but do these customizations programmatically. One of the reasons to do so is to keep all the styles in one place. In other words, it’s something like css stylesheet that can render all pages or views. Whatever the reason is, let’s try it.

Open Xcode 9 and create a new project. A dialog box will appear for selecting template. Choose single view application and press next.

Screen Shot 2014-09-14 at 2.05.25 PM

In the next box, type Product name – “Custom Label”. In Organization Identifier box, type reverse of your domain name. Choose Swift as language and press next.

 

customLabel1

From next dialog box select the location where you want to save the project and press “Create” button.

Screen Shot 2014-09-14 at 2.11.39 PM

Now open Main.storyboard from Project Navigator (If you can’t see project navigator in the left side of the screen, press Commad+O). You will see a blank View Controller in the workspace window.

 

customLabel2

Drag and drop a Label element from Utilities panel (If you can’t see Utilities Panel, press Command+Option+0) to the View Controller of the workspace (See above figure – bottom right corner).

Press Command+N (or File > New > File) to add a new file to the project. From template chooser box select Swift file and press next.Screen Shot 2014-09-14 at 2.24.46 PM

Save the file as MyCustomLabel.

customLabel3

Open MyCustomLabel.swift file.

import UIKit so that you can subclass MyCustomLabel class from UILabel.

import UIKit

Write a new subclass of UILabel and name it “MyCustomLabel”

class MyCustomLabel: UILabel {

}

We’ve to override init(coder aDecoder: NSCoder!)  function.

init(coder aDecoder: NSCoder!) {

super.init(coder: aDecoder)

}

The colour of the text that we write inside the UILabel can be changed as follows:

self.textColor = UIColor.blue

Finally, our whole code will look like :

Now, you’ve to attach this custom class with your Label. Let’s do them in 3 steps.

Go to Storyboard and select the label.

From Utility panel select the Identity Inspector.

In the class box Type MyCustomLabel

customLabel4

To see what you have done, press Command+R (or Product > Run) to run the application on simulator

How to customise UITextField in SWIFT 4.0?

Requirements:

Operating System: OS X 10.9.4+

IDE: Xcode 9

Level: Beginner to intermediate.

In my previous article I showed you how to customise UIButton. Here I’ll discuss about changing the look and feel of Text Field (UITextField)

As usual Open Xcode and create a new project. A dialog box will appear for selecting template. Choose single view application and press next.

Screen Shot 2014-09-14 at 2.05.25 PM

In the next box, type Product name. I typed Custom TextField. I’ve also used reverse of my website’s domain name com.webindream as Organization Identifier. You must choose Swift as language and press next.

Custom TextField

From next dialog box select the location where you want to save the project and press “Create” button.

Screen Shot 2014-09-14 at 2.11.39 PM

Now open Main.storyboard from Project Navigator (If you can’t see project navigator in the left side of the screen, press Commad+O). You will see a blank View Controller in the workspace window.

TextField3

 

 

Now drag and drop a TextField element from Utilities panel (If you can’t see Utilities Panel, press Command+Option+0) to the View Controller of the workspace (See above figure – bottom right corner). One more thing, don’t be confused with UITextField and UITextView.

  • UITextField: UITextField object is a control that displays editable text and sends an action message to a target object when the user presses the return button.”
  • UITextView: “The UITextView class implements the behavior for a scrollable, multiline text region.”

(Source: StackOverflow.com)

Press Command+N (or File > New > File) to add a new file to the project. From template chooser box select Swift file and press next. Screen Shot 2014-09-14 at 2.24.46 PM

Type MyCustomTextField as file name and create the file.

TextField1

Open MyCustomTextField.swift file and get ready to edit.

import UIKit as UITextField is a child class of UIKit.

import UIKit

Write a new subclass of UITextField and name it “MyCustomTextField”

class MyCustomTextField: UITextField {

}

We’ve to override init(coder aDecoder: NSCoder!)  function.

init(coder aDecoder: NSCoder!) {

super.init(coder: aDecoder)

}

First of all we’ll make the corners of the TextField round.

To do so, write the following code inside init(coder aDecoder: NSCoder!) function.

self.layer.cornerRadius = 5.0;

Now change the border color and border width with help of following 2 lines:

self.layer.borderColor = UIColor.gray.cgColor

self.layer.borderWidth = 1.5

To change the background colour of the Text Field modify backgroundColor property of UITextField:

self.backgroundColor  = UIColor.blue

The colour of the text that we write inside the Textfield can be changed as follows:

self.textColor = UIColor.white

You may be curious to customize the colour of the cursor that blinks when the TextField is focused. Don’t worry, you can do this too:

self.tintColor = UIColor.white

Finally, our whole code will look like :

 

Now, you’ve to attach this custom class with your button. Let’s do them in 3 steps.

Go to Storyboard and select the button.

From Utility panel select the Identity Inspector.

In the class box Type MyCustomTextField

Nothing is changed? No problem, press Command+R (or Product > Run) to run the application on simulator.

Voila, you’re done.

How to customise UIButton in SWIFT 4.0?

Tech experts are expecting that, objective-C will become history within a few years. We all are moving towards SWIFT – new programming language – which is more powerful and smart. It’s easier to grasp the basics of SWIFT and develop simple programs. But what about customising design elements of OS X and iOS? Can we easily customise them? Do the process is similar to Objective-C? Or should we start from scratch?

To answer all these question, we’ll discuss here customising UIButtons, UITextFields, UITextViews etc with SWIFT. In this article I’ll show you how to customise UIButton. Let’s start.

Requirements:

Operating System: OS X 10.9.4+

IDE: Xcode 9

Level: Beginner to intermediate.

First thing first. Open Xcode and create a new project. A dialog box will appear for selecting template. Choose single view application and press next.

Screen Shot 2014-09-14 at 2.05.25 PM

In the next box, type Product name. You can type anything but here I’ll write Customize Button. I’ve also used reverse of my website’s domain name com.webindream as Organization Identifier. You must choose Swift as language and press next.

Screen Shot 2014-09-14 at 2.09.51 PM

From next dialog box select the location where you want to save the project and press “Create” button.

 

Screen Shot 2014-09-14 at 2.11.39 PM

Now open Main.storyboard from Project Navigator (If you can’t see project navigator in the left side of the screen, press Commad+0). You will see a blank View Controller in the workspace window.

 

Screen Shot 2014-09-14 at 2.20.12 PM

Now drag and drop a button element from Utilities panel (If you can’t see Utilities Panel, press Command+Option+0) to the View Controller of the workspace (See above figure – bottom right corner). Get ready to customise this button.

Press Command+N (or File > New > File) to add a new file to the project. From template chooser box select Swift file. If you can’t see the Swift file, take help of the screenshot provided above. Press next.

Screen Shot 2014-09-14 at 2.24.46 PM

Type MyCustomButton as file name and create the file.

Screen Shot 2014-09-14 at 2.27.27 PM

Open MyCustomButton from Project Navigator window – if it’s already not opened.

You will see the following code:

import Foundation

First import UIKit as UIButton is a child class of UIKit.

import UIKit

Now, we’ll create MyCustomButton which will be Sub Class of UIButton :

class MyCustomButton: UIButton {

 

}

We’ve to override init(coder aDecoder: NSCoder!)  method and write super.init(coder: aDecoder) at the beginning of the method.

init(coder aDecoder: NSCoder!) {

super.init(coder: aDecoder)

}

Now, let’s add radius to the button corner.  To do so, write the following code inside init(coder aDecoder: NSCoder!) function.

self.layer.cornerRadius = 5.0;

To change the border color and border width, you can use:

self.layer.borderColor = UIColor.red.cgColor

self.layer.borderWidth = 1.5

Here I’ve used red color you can use any other colour you like.

Now, lets change the background color of the button. That’s very easy:

self.backgroundColor  = UIColor.blue

However, to change the text color of the button you can’t use anything like: self.titleColor. Instead, use the following line:

self.tintColor = UIColor.white

Finally, our whole code will look like :

Now, you’ve to attach this custom class with your button. Let’s do them in 3 steps.

Go to Storyboard and select the button.

From Utility panel select the Identity Inspector.

In the class box Type MyCustomButton

Nothing is changed? No problem, press Command+R (or Product > Run) to run the application on simulator.

Voila, you’re done.

Swift - Button customisation