• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Xcode

Internationalization and localization of Apps in Xcode 6 and Swift

August 7, 2014 By Ravi Shankar 25 Comments

Internationalisation and Localization of apps is essential when you want the apps to seamlessly support different languages and region. Internationalization refers to process of providing a framework to the app for supporting multiple languages. And Localization refers to the process of making your app to support a particular locale such as German

In this tutorial, we are going to see an example app that supports text, number, date, currency and image localisation for English and German languages. This is done by following the below mentioned steps

  • Use NSNumberFormatter, NSDateFormatter for Number, Currency and Date values.
  • Internationalization of Storyboard.
  • Internationalization of text.
  • Internationalization of images.

English

201408072015.jpg

German

 

201409302136.jpg

Download source code from GitHub

Create a new project by clicking File menu -> New -> Project

201408071400.jpg

Select the template for the Project as Single View Application.

201408071401.jpg

‘

In the next screen, provide a name for the project as “Localisation Demo” and select the Language as “Swift” then specify a location and save the project.

User Interface changes – UILabels and UIImageView on ViewController

 

Navigate to Main.storyboard, click default View Controller. Drag and drop 9 Labels and 1 ImageView from Object Library on to Storyboard. These labels are used for displaying the caption and values as shown in the below screenshot.

201408071642.jpg

Declaring IBOutlets for UIControls

Click ViewController.swift in project navigator and add the following IBOutlets after the class declaration.

[code language=”swift”]@IBOutlet var textLabel: UILabel!

@IBOutlet var numberLabel: UILabel!

@IBOutlet var currencyLabel: UILabel!

@IBOutlet var dateLabel: UILabel!

@IBOutlet var imageView: UIImageView!
[/code]

Navigate back to Main.storyboard and connect labels and imageView to the respective outlets.

201408071658.jpg

Populate values for the controls.

 

Click ViewController.swift in Project Navigator and create a new function with name as populateValues

[code language=”swift”]func populateValues() {
textLabel.text = “Good Morning”
numberLabel.text = “9999999.999”
currencyLabel.text = “50000”
dateLabel.text = “07/08/2014”
imageView.image = UIImage(named: “hello”)
}[/code]

The above function populates values for all the controls. The values which are assigned for the fields will be displayed in the screen without localization format. Then add this function as part of ViewDidLoad function.

[code language=”swift”]override func viewDidLoad() {
super.viewDidLoad()
populateValues()
}[/code]

Using Add Files to option, add the image hello.png to the Project folder.

201408071755.jpg201408071756.jpg

Now if you compile and run the project on iOS simulator, you should see the follow screen with values for the labels and image view.

201408071759.jpg

We do not see any formatting applied for Number, Date and Currency Values. Now let us see how to use NSNumberFormatter for formatting number and currency field and NSDateFormatter for formatting date field. Add the following properties after populateValues function in ViewController.swift file.

[code language=”swift”]var numberFormatter: NSNumberFormatter {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
return formatter
}
[/code]

[code language=”swift”]
var currencyFormatter: NSNumberFormatter {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
return formatter
}[/code]

 

[code language=”swift”]var dateFormatter: NSDateFormatter {
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .MediumStyle
return formatter
}
[/code]

 

In the above functions, we are creating respective formatter instances and setting the corresponding styles such DecimalStyle, CurrencyStyle then MediumStyle for date and time values. Now we need to update populateValues function to use these properties for displaying the values.

[code language=”swift”]func populateValues() {
textLabel.text = “Good Morning”
numberLabel.text = numberFormatter.stringFromNumber(9999999.999)
currencyLabel.text = currencyFormatter.stringFromNumber(5000)
dateLabel.text = dateFormatter.stringFromDate(NSDate())
imageView.image = UIImage(named: “hello”)
}

[/code]

Now after applying the correct format, iOS Simulator will use the default system region to display the values for number, currency and date fields

201408071834.jpg

Adding support for another language to your Xcode Project

In order to enable support for German language, first we need to add that language to the Project. This can be done by using the option available as part of Project target. Select the Project folder then the Project target.

201408071715.jpg

Navigate to the Localization section and click the + sign then select German (de) from the list.

201408071718.jpg

Choose the default files listed in the below screen and click Finish.

201408071720.jpg

Now you should see support German language under Localizations section.

201408071720.jpg

Add Localization for controls in Storyboard

First let us see how to add support for another language for the Caption controls in Main.storyboard.

201408071728.jpg

Expand Main.storyboard and click Main.strings (German) . Now enter the German equivalent for Date, Currency, Number and Image as Datum, Währung, Anzahl and Bild. And for rest of the controls, localization will be done in the code.

201408071735.jpg[code language=”plain”]

/* Class = “IBUILabel”; text = “Date :”; ObjectID = “0sh-CK-26C”; */
“0sh-CK-26C.text” = “Datum :”;

/* Class = “IBUILabel”; text = “Number :”; ObjectID = “AeO-ot-XWj”; */
“AeO-ot-XWj.text” = “Anzahl :”;

/* Class = “IBUILabel”; text = “number”; ObjectID = “XDV-eF-gQk”; */
“XDV-eF-gQk.text” = “number”;

/* Class = “IBUILabel”; text = “Image :”; ObjectID = “bvG-x6-Tpx”; */
“bvG-x6-Tpx.text” = “Bild :”;

/* Class = “IBUILabel”; text = “Currency :”; ObjectID = “tVi-KF-Xgb”; */
“tVi-KF-Xgb.text” = “Währung :”;[/code]

Testing Localization changes in iOS Simulator

The changes to Main.storyboard (German) and NSNumberFormatter and NSDateFormatter will have no effect until we set the language and region to German in Xcode debug environment. Click Set the active scheme option and select Edit Scheme from the list.

201408071850.jpg

Navigate to Options under Debug Environment and select German and Germany for Application Language and Application Region.

201408071852.jpg

Now running the app on the iOS simulator should display the captions in german language and apply formats for number, date and currency fields based on German region.

201408071855.jpg

Internationalization of Text using NSLocalizedString

“Good Morning” has to be displayed in the corresponding German language i.e “Guten Morgen”. Add a new File to the project of type Strings and provide a name as Localizable.strings.

201408071912.jpg201408071913.jpg

Select Localizable.Strings in Project Navigator and click Localize button available under File Inspector.

201408071915.jpg

Then Select English in the Localize drop down and make sure to mark German in the Localization section under File Inspector.

201408071917.jpg201408071918.jpg

Now you should be able to expand Localizable.Strings under Project Navigator and see separate files for English and German.

201408071921.jpg

Add the following line in Localizable.Strings (English)

GOOD_MORNING=“Good Morning”;

Add the following line in Localizable.Strings (German)

GOOD_MORNING=“Guten Morgen”;

Now add the corresponding code to use the values from Localizable.Strings file. Click ViewController.swift and change

textLabel.text = “Good Morning”

to

textLabel.text = NSLocalizedString(“GOOD_MORNING”,comment:“Good Morning”)

NSLocalizedString will lookup for the corresponding entry in Localizable.Strings file for the supplied key. Running the app on iOS simulator should not display the German equivalent for “Good Morning”

201409302137.jpg

Internationalization of Images

In the above screenshot, you could see that text in the image is still in English. So we need to add the corresponding image that contains German text and make changes to pick up the entry based on the Application Language. After selecting hello.png in Project navigator, click Localize button under File Inspector. This should provide you with the option to Localize the file in English and German.

201408071954.jpg

Make sure to tick both English and German under Localization section in File Inspector.

201408071955.jpg

Open the Project folder in Finder tool and this should contain two folder for the languages de and en.

201408072004.jpg

Now copy hello.png with german text to de.lproj folder. Do a clean build and run the app on iOS simulator with language and region set to German.

201409302137.jpg

Download source code from GitHub

Filed Under: ios, iPad, iPhone, Programming, Xcode Tagged With: Internationalization, iPad, Localization, Swift, Xcode, Xcode 6

UIGestureRecognizer in Swift

July 23, 2014 By Ravi Shankar 9 Comments

In this short tutorial, we will see the steps required for implementing UIGestureRecognizer in Swift programming language. Let us take the previous Stop Watch demo code and implement tap, double tap and swipe gestures. You can download source code for Stop Watch from here.

201407231513.jpg

The following features will be implemented using the UIGestureRecognizer.

  • Tap – Starts the timer.
  • Double Tap – Stops the timer
  • Swipe (from left to right) – Resets the timer.

Remove the buttons

Since we are replacing the buttons with gestures, these buttons can be removed from the View Controller. Navigate to Main.storyboard and select the Start and Stop buttons and delete them. Make sure the timer label is centre aligned both vertically and horizontally. Then click Reset to Suggested Constraints under Resolve Auto Layout Issues option.

201407231527.jpg

Write Gestures code

Click SWViewController.swift file in the Project navigator and navigate to viewDidLoad function. Then add the following code to viewDidLoad method

  override func viewDidLoad() {

super.viewDidLoad()

  

let aSelector : Selector = “start:”

let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)

tapGesture.numberOfTapsRequired = 1

view.addGestureRecognizer(tapGesture)

  

}

First this creates a constant to hold the selector argument which will be used when creating UITapGestureRecognizer. We are reusing the function that was used for the Start button.

Then we specify the numberOfTapsRequried and add the gesture as part of the view. Now repeat this for the stop button as well but for double tap.

  let bSelector : Selector = “stop:”

let doubleTapGesture = UITapGestureRecognizer(target: self, action: bSelector)

doubleTapGesture.numberOfTapsRequired = 2

view.addGestureRecognizer(doubleTapGesture)

  

tapGesture.requireGestureRecognizerToFail(doubleTapGesture)

The only difference is the number of taps required is specified as 2 and we are specifying that the single tap function will be called only when gesture is not double tap. Now if you try to run this project in the simulator, you should be able start and stop the timer using tap and double tap gestures.

Adding Swipe Gesture

When the user does a swipe from left to right, the values in the timer label must be set to 00:00:00. We can do this by using the UISwipeGestureRecognizer. Let us first the add function that resets the timer label.

  @IBAction func reset(sender: AnyObject) {

displayTimeLabel.text = “00:00:00”

}

Then add the following code to viewDidLoad method

  let cSelector : Selector = “reset:”

let rightSwipe = UISwipeGestureRecognizer(target: self, action: cSelector)

rightSwipe.direction = UISwipeGestureRecognizerDirection.Right

view.addGestureRecognizer(rightSwipe)

When a swipe from left to right is done the reset function is called. The viewDidLoad function with all the Gesture Recognizer should look as shown below.

  override func viewDidLoad() {

super.viewDidLoad()

  

let aSelector : Selector = “start:”

let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)

tapGesture.numberOfTapsRequired = 1

view.addGestureRecognizer(tapGesture)

  

let bSelector : Selector = “stop:”

let doubleTapGesture = UITapGestureRecognizer(target: self, action: bSelector)

doubleTapGesture.numberOfTapsRequired = 2

view.addGestureRecognizer(doubleTapGesture)

  

tapGesture.requireGestureRecognizerToFail(doubleTapGesture)

  

let cSelector : Selector = “reset:”

let rightSwipe = UISwipeGestureRecognizer(target: self, action: cSelector)

rightSwipe.direction = UISwipeGestureRecognizerDirection.Right

view.addGestureRecognizer(rightSwipe)

}

Try running the project in simulator and check out tap, double tap and swipe gestures.

201407231555.jpg

Source code

Filed Under: Develop, ios, Xcode Tagged With: Swift, UIGestureRecognizer, UISwipeGestureRecognizer, UITapGestureRecognizer, Xcode

Simple StopWatch app in Swift

July 22, 2014 By Ravi Shankar 53 Comments

In this tutorial, we will see the steps for creating simple StopWatch app in Swift Programming language as shown in the below screenshot.

SimpleStopWatch demo

Click File menu -> New -> select Project from menu list.

Single View Application Xcode

Choose the template as Single View Application and click Next button.

Xcode select language as Swift

Enter name of the Product, Language as Swift then click Next to specify a folder and save the project.

Project Navigator in Xcode

Navigate to Project Navigator and select Main.storyboard. Using the Attributes Inspector, change the background colour for the ViewController to Dark Gray Colour

Attributes Inspector for View Controller

Navigate to Object Library, drag and drop UILabel to View Controller. Then align the label horizontally centred to the View Controller. Using the Attributes Inspector enter the label text as 00:00:00, change the colour to White, make the text centre aligned and increase the the font size to 27.0

Attributes Inspector for UILabel

Now drag and drop two buttons for starting and stopping the timer. Change the button text to Start and Stop respectively and set the Text Color to white.

201407221034.jpg

Now select ViewController.swift in the Project Navigator and delete the file, select Move to Trash in the Confirmation box.

201407221037.jpg201407221054.jpg

Let us add a new UIViewController file, right click on the SimpleStopWatch folder and select New File from the menu list.

201407221039.jpg

Select the template for the new file as Cocoa Touch Class (under iOS), then click Next

201407221042.jpg

Enter the name of the class as SWViewController, Subclass as UIViewController and Language as Swift. Then click Next and choose the Project folder to save the file.

201407221044.jpg

Navigate to SWViewController.swift and add a IBOutlet for UILabel.

[code language=”swift”]@IBOutlet var displayTimeLabel: UILabel!
[/code]

Then add two IBActions method for the two buttons, Start and Stop.

[code language=”swift”]
@IBAction func start(sender: AnyObject) {
}

@IBAction func stop(sender: AnyObject) {
}
[/code]

 

Navigate to Main.storyboard, select View Controller and specify the class name as SWViewController using the Identify Inspector

Identity Inspector for Class name

Now you should be able to see the IBActions and IBOutlet defined in the class file using Connection Inspector

Connections Inspector in Xcode 6

Drag and connect the UILabel with the IBOutlets, similarly connect IBActions with the buttons and specify the event as Touch Up Inside.

201407221100.jpg

Select the ViewController under View Controller Scene, click the Resolve Auto Layout Issues option and select Reset to Suggested Constraints. This would ensure that the alignment of controls remains the same for different screen size.

201407221108.jpg

Now if you try to run this project on Simulator, the screen would be as shown below. Nothing should happen on clicking the two buttons as we are yet to add the functionality.

201407221111.jpg

Write Code logic for StopWatch

Navigate to SWviewController.swift file and new function name as updateTime. This function will be used for calculating the time in minutes, seconds and fraction of milliseconds.

Add a new class level variable to the class for storing the start time.

[code language=”swift”]var startTime = NSTimeInterval()[/code]

Then add the following code in updateTime method. This is used for calculating the StopWatch time and assigning the value to the UILabel.

[code language=”swift”]</pre>
func updateTime() {

var currentTime = NSDate.timeIntervalSinceReferenceDate()

//Find the difference between current time and start time.

var elapsedTime: NSTimeInterval = currentTime – startTime

//calculate the minutes in elapsed time.

let minutes = UInt8(elapsedTime / 60.0)

elapsedTime -= (NSTimeInterval(minutes) * 60)

//calculate the seconds in elapsed time.

let seconds = UInt8(elapsedTime)

elapsedTime -= NSTimeInterval(seconds)

//find out the fraction of milliseconds to be displayed.

let fraction = UInt8(elapsedTime * 100)

//add the leading zero for minutes, seconds and millseconds and store them as string constants

let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)

//concatenate minuets, seconds and milliseconds as assign it to the UILabel

displayTimeLabel.text = “\(strMinutes):\(strSeconds):\(strFraction)”

}[/code]

Add a new class level NSTimer variable as shown below.

[code language=”swift”]</pre>
var timer = NSTimer()[/code]

Navigate to Start IBAction function and add the following the code.

 

[code language=”swift”]@IBAction func start(sender: AnyObject) {
let aSelector : Selector = “updateTime”
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
[/code]

This would start a timer and it repeats at regular time interval of 0.01. Here we specify the “updateTime” function which gets called regularly after the specified interval. We also initialise the startTime variable to the current time. Now when the user taps on Stop button, timer is invalidated and set to nil.

[code language=”swift”]
@IBAction func stop(sender: AnyObject) {
timer.invalidate()
timer == nil
}
[/code]

If you try to run this app on the simulator, you should notice the start and stop functionality works and time is getting displayed in the Label. But the user can repeatedly tap the Start button. So when the clock is running if the user taps the Start button, clock restarts again. We can prevent this by adding the following check to start the timer only when the timer is not running.

[code language=”swift”]@IBAction func start(sender: AnyObject) {
if !timer.valid {
let aSelector : Selector = “updateTime”
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
}[/code]

Download the source code from here

Filed Under: Develop, ios, Programming, Xcode Tagged With: StopWatch, Swift, Xcode

How to rename project in Xcode

July 21, 2014 By Ravi Shankar 3 Comments

Xcode provides users with the option to rename the project. You can do this in Xcode 6 and Xcode 5 by following the below mentioned steps.

201407210907.jpg

Navigate to Project Navigator, select the Project. After entering the new name for the Project, press Return on the Keyboard. In this example, I am changing the name of project from StopWatch to MyStopWatch.

Once you press enter on the keyboard, the following confirmation screen will be displayed. Make sure you are Ok with the displayed changes then click Rename option.

201407210908.jpg

Filed Under: Xcode Tagged With: Rename Project, Xcode

Insertion Sort

July 3, 2014 By Ravi Shankar 2 Comments

Insertion Sort algorithm does the following

  • Keeps the sorted numbers from left to right.
  • Compares the left with right and interchanges the number if left is greater than right.

Here is code snippet of Insertion Sort in Swift.

[code language=”swift”]var inputArr:[Int] = [Int]()

// generate random numbers
for rIndex in 0..&lt;10 {
inputArr.append(((Int(arc4random()) % 100)))
}

func insertionSort(var inputArray :[Int]) -&gt; [Int] {
var jIndex:Int,kIndex:Int

for kIndex in 1.. 0 &amp;&amp; inputArray[jIndex-1] &gt;= temp ) {
inputArray[jIndex] = inputArray[jIndex-1]
–jIndex
}
inputArray[jIndex] = temp
}

return inputArray
}

insertionSort(inputArr)[/code]

Filed Under: ios, Mac, Programming, Xcode Tagged With: algorithm, insertion Sort, Swift, Xcode

Reverse a String in Swift

July 2, 2014 By Ravi Shankar 5 Comments

Here is a simple code snippet written in Swift programming language for reversing a string.

import Cocoa


//Assigning a value to a String variable

var str = "Hello, playground"


//Create empty character Array.

var strArray:Character[] = Character[]()


//Loop through each character in the String

for character in str {

//Insert the character in the Array variable.

strArray.append(character)

}


//Create a empty string

var reversedStr:String = ""


//Read the array from backwards to get the characters

for var index = strArray.count - 1; index >= 0;--index {

//Concatenate character to String.

reversedStr += strArray[index]

}


reversedStr


the shorter version to reverse is (thanks Andreas)


var str = “Hello, playground”

var reverseStr = “”

for character in str {

reverseStr = character + reverseStr

}

Reverse a String in Swift Programming language
This code snippet demonstrates the following.

  • How to assign a value to variable.
  • How to create an Array of Characters and assign empty value.(Character)
  • Iterate over the string using for-in loop.
  • How to add new elements to an Array.
  • How to create empty String variable.
  • Use the standard for loop to traverse through an array.
  • Concatenate Strings and character
  • Using for .. in

Filed Under: ios, Programming, Xcode Tagged With: Reverse String, Swift, Xcode

No such module Cocoa

July 1, 2014 By Ravi Shankar 2 Comments

No such module Cocoa error message is displayed when the type of playground file selected is iOS instead of OS X. Make sure to select Playground under OS X if you want to use Cocoa framework and go for UIKit incase of iOS

Choose a template from your new file

Another alternate way is to change the template using the Playground Settings. Use the toggle option to show the Utilities.

Show the Utilities on Playground

Navigate to Playground Settings section, click the Platform drop down and select OS X from the list. This should also resolve the No such module error on Playground.

Playground Settings

Filed Under: Develop, Programming, Xcode Tagged With: error, Playground, Xcode

Selection Sort

July 1, 2014 By Ravi Shankar Leave a Comment

Selection Sort algorithm does the same amount of comparison( N*(N-1)/2 ) like bubble sort but the number swaps (N) is reduced drastically. This sort algorithm traverse through all the items, picks the smallest number and swaps it with left most item. Then the step is repeated for the next smallest number until it reaches the end of the elements in array. Listed below is the code for Selection Sort and screenshot of this algorithm executed in Playground.

import UIKit

func swapNumbers(index1 :Int,index2: Int) {

let temp = inputArr[index1]

inputArr[index1] = inputArr[index2]

inputArr[index2] = temp

}


var inputArr = Int[]()


// generate random numbers

for rIndex in 0..10 {

inputArr.append(((Int(arc4random()) % 100)))

}


inputArr


var minIndex: Int = 0


func selectionSort(inputArray :Int[]) {

for var index:Int = 0; index < inputArr.count-1; ++index {

minIndex = index

for (var jIndex: Int = index + 1; jIndex < inputArr.count-1; ++jIndex) {

if inputArr[jIndex] < inputArr[minIndex] {

minIndex = jIndex

}

}

swapNumbers(index, minIndex)

}

}


selectionSort(inputArr)


inputArr

  1. swapNumber function is used for swapping the numbers in the array for the given indexes.
  2. The numbers for the input array is randomly generated using the arc4random function.
  3. selectionSort function is the selectionSort algorithm that starts from the first number in the array and compares it with other elements and finds smallest one (stores the index as minIndex).
  4. Then swaps the smallest number with the left most and repeats these steps for the next number in the array until it reaches end of array.


Selection Sort algorithm in Swift

Filed Under: Develop, ios, Xcode Tagged With: algorithm, Selection Sort, Swift, Xcode

  1. Pages:
  2. «
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6
  9. 7
  10. 8
  11. »
« Previous Page
Next Page »

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to block keywords in Jio broadband
  • How to disable opening an app automatically at login in Mac
  • How to set preferred Wifi network on Mac
  • Attribute Unavailable: Estimated section warning before iOS 11.0
  • How to recover Firefox password from Time Machine backup

Pages

  • About
  • Privacy Policy
  • Terms and Conditions

Copyright 2022 © rshankar.com

Terms and Conditions - Privacy Policy