iOS Tip: Using IBDesignable for previewing custom views

Xcode 6 offers you an amazing feature that help developers save A LOT of time by allowing you to preview the output even without having to run the application for your custom drawn views.

IBDesignable as it is called, when applied on your custom view allows you to preview it directly on the storyboard before you having to run the code after any change.


Just prefix your custom view with IBDesignable Yes. and that’s all you need to do!!🙂


You can try this out using the iOS single view application template in Xcode.

Here’s the code within the custom UIView subclass in the file simpleView.swift.


class simpleView: UIView {
    // Override Draw Rect method to perform custom drawing.
    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()

        // ************************************************************
        // Paint the View Blue
        CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)  // Set fill color
        CGContextFillRect(context, rect) // Fill rectangle using the context data

        // ************************************************************
        // Paint a rect inside view Green
        let greenRect = CGRectInset(rect, 30, 30) // Inset will reduce the size of 'rect' by 30 in x and 30 in y.
        CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor) // Set fill color
        /* Fill `rect' with the current fill color. */
        CGContextFillRect(context, greenRect) // Fill rectangle using the context data

Now you can add this view as a subview to any view in your storyboard. The changes you do in the view will immediately reflect in the storyboard (actually it still needs to build so it might take a little while ;)).


Debugging with IBDesignable

Better yet, you can debug the code within your custom view class using IBDesignable without running the app. All you need to do is add/enable breakpoints in your custom view code and then select the corresponding view in storyboard and click on Xcode: Editor -> Debug Selected Views and voila! There it is.


And.. You’re welcome!😉

Further Reads:

  1. Apple Developer: Creating a Custom View That Renders in Interface Builder
  2. Apple Developer: Debugging a Custom View Without Running Your App
  3. NSHipster: IBInspectable / IBDesignable

Drawing using Core Graphics [Swift]

Learning to draw content is important in iOS. Even if you have not done it before, it is almost certain you might do it in the future. Drawing helps achieve high quality graphics independent of the device and at the same time provides great performance using the least memory. Drawing in iOS can be done using OpenGL or in native using Quartz, Core Animation or UIKit.

In this guide, we use the Core Graphics Framework which is based on Quartz for drawing in iOS.

The Core Graphics framework is a C-based API that is based on the Quartz advanced drawing engine. It provides low-level, lightweight 2D rendering with unmatched output fidelity. You use this framework to handle path-based drawing, transformations, color management, offscreen rendering, patterns, gradients and shadings, image data management, image creation, masking, and PDF document creation, display, and parsing.

Apple Developer: Core Graphics Framework Reference

All drawings are performed on an UIView object. A UIView subclass is created and the drawing code is added to the drawRect: method by overriding it.

Whenever a view is first displayed on the screen or is updated, iOS prompts the view to draw its contents by calling the drawRect: method. The drawRect: method is called in the following cases:

  • When another view overlaps on to this view/changes its position.
  • When the view is hidden/made visible explicitly or by scrolling it offscreen.
  • Programatically by calling the setNeedsDisplay method on the view.

Note: The drawRect: method should never be called directly on the view. Instead, if the view needs to be re-drawn, call the setNeedsDisplay method.

Before we begin with the drawing, It is better to make yourself familiar with the co-ordinate systems and points/pixel differentiation. You can read about this here: Apple Developer: Drawing and Printing Guide for iOS


Drawing onto a view involves the following steps.

(To follow up with this tutorial, you can begin by creating a simple single view application template. Xcode: File -> New -> Project Select iOS: Single View Application)

1. Creating a custom view

For adding the drawing code, create a subclass of UIView by adding a swift file to the project (Xcode: File -> New -> File Select iOS: Source -> Swift File) and call it “simpleView“. Create a subclass of UIView as below and override the drawRect: method for writing the drawing code.

import UIKit

class simpleView: UIView {
    // Override Draw Rect method to perform custom drawing.
    override func drawRect(rect: CGRect) {

In the sample project, open the main.storyboard, add a new UIView to the ViewController’s view as a subview and set the class of this view to our custom view simpleView. Set the dimensions of the subview and add any necessary constraints. (For more on Constraints and AutoLayouts, read the post Auto Layouts in iOS.)

2. Obtaining the Graphics Context

For creating/drawing on a view, we need to initially obtain what is known as a Graphics Context. iOS will prepare for drawing based on this context for different destinations such as on-screen, bitmap or PDF. This context will only be available for the lifetime of drawRect: method.

Obtaining the Graphics Context:
	let context = UIGraphicsGetCurrentContext()

A graphics context represents a drawing destination. It contains drawing parameters and all device-specific information that the drawing system needs to perform any subsequent drawing commands.

Apple Developer: Quartz 2D Programming Guide

3. Setting the Graphics Context Parameters

Conceptually, a graphics context is an object that describes where and how drawing should occur, including basic drawing attributes such as the colors to use when drawing, the clipping area, line width and style information, font information, compositing options, and so on.

Apple Developer: Drawing and Printing Guide for iOS

Example for setting the fill color of the context
	CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)

There are a variety of aspects you can set on the graphic context as described above. A list of which is provided in the Apple Developer: CGContext Reference and a glossary of terms is available in the Apple Developer: Core Graphics Framework Reference.

4. Creating Paths

Paths are shapes created using a lines/curves(Bézier Curves) which are vectors. And these paths need to be drawn onto the graphics context for them to be displayed on the screen.

You can use the available convenience methods of UIKit to create simple paths like rectangles/circles. For more complex paths one can make use of the UIBezierPath class to construct the required shape.

Example of creating and drawing/filling the view using convenience methods:
        CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)  // Set fill color
        CGContextFillRect(context, rect) // Fill rectangle using the context data
Example of creating a triangle path using UIBezierPath:
        // Imagine a triangle resting on the bottom of the container with the base as the width of the rectangle, and the apex of the triangle at the top center of the container
        // The co-ordinates of the rectangle will look like
        // Top = (x: half of Container Width, y: 0 - origin)
        // Bottom Left = (x: 0, y: Container Height)
        // Bottom Right = (x: Container Width, y: Container Height)

        // Create path for drawing a triangle
        var trianglePath = UIBezierPath()
        // First move to the Top point
        trianglePath.moveToPoint(CGPoint(x: self.bounds.width/2, y: 0.0))
        // Add line to Bottom Right
        trianglePath.addLineToPoint(CGPoint(x: self.bounds.width, y: self.bounds.height))
        // Add line to Bottom Left
        trianglePath.addLineToPoint(CGPoint(x: 0.0, y: self.bounds.height))
        // Complete path by drawing path to the Top
        trianglePath.addLineToPoint(CGPoint(x: self.bounds.width/2, y: 0.0))

More on Drawing shapes using Bézier Paths here:

5. Drawing Paths

The paths created in the previous steps are only imaginary. i.e., the paths are not drawn onto the screen yet. Paths can be stoked/filled using the below functions:

 CGContextFillPath(c: CGContext!) // Fills the path using the context parameters
 CGContextStrokePath(c: CGContext!) // Draws/strokes the path using the context parameters

Aaand it’s done!🙂

So far we obtained the context, set it’s parameters, created paths and finally drew on the path. Below are few simple drawing examples illustrating how the above steps come together and complete the drawing.


1. Stroking and filling Rectangles and Circles




    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()

        // ************************************************************
        // Paint the View Blue
        CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)  // Set fill color
        CGContextFillRect(context, rect) // Fill rectangle using the context data

        // ************************************************************
        // Paint a rect inside view Green
        let greenRect = CGRectInset(rect, 30, 30) // Inset will reduce the size of 'rect' by 30 in x and 30 in y.
        CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor) // Set fill color
        /* Fill `rect' with the current fill color. */
        CGContextFillRect(context, greenRect) // Fill rectangle using the context data

        // ************************************************************
        // Stroke a white rect inside the inner Green rectangle
        let whiteRect = CGRectInset(greenRect, 30, 30) // Inset will reduce the size of 'rect' by 30 in x and 30 in y.
        CGContextSetStrokeColorWithColor(context, UIColor.whiteColor().CGColor) // Set stroke color: (Note this is different from fill color)
//        CGContextSetLineWidth(context, 2.0) // Line width to be used for strokes
        /* Stroke `rect' with the current stroke color and the current linewidth. */
//        CGContextStrokeRect(context, whiteRect) // Fill rectangle using the context data
        // Alternate to the above two lines
        /* Stroke `rect' with the current stroke color, using `width' as the the
        line width. */
        CGContextStrokeRectWithWidth(context, whiteRect, 2.0) // Fill rectangle using the context data
        // ************************************************************
        // Create a red circle in the center
        let circleRect = CGRectInset(whiteRect, 30, 30) // Inset will reduce the size of 'rect' by 30 in x and 30 in y.
        CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor) // Inset will reduce the size of 'rect' by 30 in x and 30 in y.
        CGContextFillEllipseInRect(context, circleRect) // Fill an ellipse confined by the edges of the rect (Note that in this case, since the width and breadth of the rect is same, the resulting ellipse is a circle.)


2. Drawing a Triangle using Bezier Path




    override func drawRect(rect: CGRect) {
        // Drawing a triangle using UIBezierPath
        let context = UIGraphicsGetCurrentContext()
        // Paint the View Blue before drawing the traingle
        CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)  // Set fill color
        CGContextFillRect(context, rect) // Fill rectangle using the context data
        // Imagine a triangle resting on the bottom of the container with the base as the width of the rectangle, and the apex of the traingle at the top center of the container
        // The co-ordinates of the rectangle will look like
        // Top = (x: half of Container Width, y: 0 - origin)
        // Bottom Left = (x: 0, y: Container Height)
        // Bottom Right = (x: Container Width, y: Container Height)

        // Create path for drawing a triangle
        var trianglePath = UIBezierPath()
        // First move to the Top point
        trianglePath.moveToPoint(CGPoint(x: self.bounds.width/2, y: 0.0))
        // Add line to Bottom Right
        trianglePath.addLineToPoint(CGPoint(x: self.bounds.width, y: self.bounds.height))
        // Add line to Bottom Left
        trianglePath.addLineToPoint(CGPoint(x: 0.0, y: self.bounds.height))
        // Complete path by drawing path to the Top
        trianglePath.addLineToPoint(CGPoint(x: self.bounds.width/2, y: 0.0))
        // Set the fill color
        CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor)
        // Fill the triangle path

3. Drawing an Arc/Semi-Circle using Bezier Path




    override func drawRect(rect: CGRect) {
        // Drawing an Arc/Semi-Circle using UIBezierPath
        let context = UIGraphicsGetCurrentContext()
        // Paint the View Blue before drawing the Semi-Circle
        CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)  // Set fill color
        CGContextFillRect(context, rect) // Fill rectangle using the context data
        // Imagine the setting Sun. Please go a bit further in your imagination so that the Sun looks like a perfect circle which is perfectly sliced in the middle by the perfectly horizontal horizon.🙂
        // This can be drawn by having two parameters
        // Bottom Left = (x: 0, y: Container Height)
        // Bottom Right = (x: Container Width, y: Container Height)
        // Create path for drawing a triangle
        var semiCirclePath = UIBezierPath()
        // Add Semi-Circle Arc from Bottom Left to Bottom Right
        semiCirclePath.addArcWithCenter(CGPointMake(self.bounds.width / 2, self.bounds.height), radius: self.bounds.width / 2, startAngle: CGFloat(M_PI), endAngle: 0, clockwise: true)
        // Notice that the angle is measured counter-clockwise from right. 
        // You might think that since the path is not complete, this might not work.
        // But the fill method does this for you🙂
        // Set the fill color
        CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor)
        // Fill the triangle path

The fill method used above implicitly closes any open paths before filling it.

If you have any questions, do leave it in the comments section below. Thanks for reading!

And one more thing. Ever heard of IBDesignable? No? It makes your life a lot easier when you are drawing. Read more about it here: iOS Tip: Using IBDesignable for previewing custom views

Interesting Reads


Related Books

Viewing PDF and iWork Documents in iOS

Viewing PDF’s and iWork documents in iOS is very simple (If you only have to view the document). So simple in fact that I actually do not have to write about it😉. So you can rather consider this a place to get a snippet of code for viewing documents in your application.

There are more than one ways you can do this based on your requirement.

1. Using a UIWebView

UIWebView can be used to load documents as well along with loading URL’s. It is especially useful if you have to load different files/urls in your application and the user needs to only view the documents.
Opening a local PDF file in UIWebView can be done by instantiating a UIWebView, adding it to your view as a subview and loading a request with the local file path as the URL.

        // Create a webview instance and add it to your view.
        let webview = UIWebView()
        webview.frame = self.view.bounds
        // loacate a file and create a URL request with the file URL and load it to the webview
        if let fileURL = NSBundle.mainBundle().pathForResource("SamplePDF", ofType: "pdf") { // Use if let to unwrap to fileURL variable if file exists
            let theFileURL = NSURL(fileURLWithPath: fileURL)

And.. that’s it! Better yet, you can open any iWork document files or even redirect to an external URL using this method.

2. Using QLPreviewController of Quick Look Framework

QLPreviewController provides the UI for displaying the documents as well as automatically provides action menu with print/share options. It even provides UI to display documents as a list if there is more than one document and automatically handles the UI for previewing the selected document.

For using the QLPreviewController we will first have to import the QuickLook framework as below.

import QuickLook

Make your controller correspond to the QLPreview Datasource and Delegate protocols

class ReaderViewController: UIViewController, QLPreviewControllerDataSource, QLPreviewControllerDelegate

Similar to a UITableView, it enables a controller to register as the datasource to provide the required data. QLPreviewControllerDataSource has two required methods that needs to be implemented as described below. It also has a delegate protocol for view presentation callbacks which is optional.

    //  Simple method to wrap the presenting of QLPreviewController
    func loadDocUsingQLPreview() {
        let previewController = QLPreviewController()
        previewController.dataSource = self
        self.presentViewController(previewController, animated: true, completion: nil)
    // QLPreviewControllerDataSource required methods
    func numberOfPreviewItemsInPreviewController(controller: QLPreviewController!) -> Int {
        return 1
    func previewController(controller: QLPreviewController!, previewItemAtIndex index: Int) -> QLPreviewItem! {

        if let fileURL = NSBundle.mainBundle().pathForResource("SamplePDF", ofType: "pdf") { // Use if let to unwrap to fileURL variable if file exists
            return NSURL(fileURLWithPath: fileURL)
        return nil;

The two required datasource methods are:

  • numberOfPreviewItemsInPreviewController: to specify the number of items to be previewed.
  • previewController: previewItemAtIndex: to provide a QLPreviewItem for the selected index. Since this is a category of NSURL, you can directly return an NSURL as mentioned in the documentation (see below). It also allows customisation to provide a Title along with URL for which you will have to create your custom object.

The methods in this protocol are also declared as a category on the NSURL class. As a result, you can use NSURL objects directly as preview items—provided that you want to use the default titles of those items. A default title is the last path component of an item’s URL. If you want to supply your own preview item titles, create your own preview item objects that adopt this protocol.
– Apple: QLPreviewItem Protocol Reference for iOS: QLPreviewItem

Advantages using QLPreviewController over UIWebView

  • Handles Presentation and loading of documents.
  • Delegate methods to notify on view controller presentation calls.
  • Nicely displays multiple documents as preview and allows user to manually select and view documents.
  • Automatically provides a navigation bar with a Done and an Action button to share/print the document and automatically animates and hides while reading.
  • More control over the preview process than UIDocumentInteractionController class.
Multiple File Selection Option
Multiple File Selection Option
File Action Menu
Document Action Menu
Document Preview Screen
Document Preview Screen

3. Using UIDocumentInteractionController

When your app needs to interact with files it cannot preview or open on its own, use a UIDocumentInteractionController object to manage those interactions.
Apple: Document Interaction Programming Topics for iOS: Previewing and Opening Files

For displaying documents, UIDocumentInteractionController also uses QLPreviewController so the preview UI is same as that in our previous implementation.

Reasons for using UIDocumentInteractionController:

  • Previewing the document along with automatic handling of all interactions related to file preview and menu display.
  • Provides option to print/share/open the document using another application without having to preview/if cannot be previewed.
  • Delegate methods for view transitions and to track user interactions with menu items.

For previewing documents using UIDocumentInteractionController, our view controller should correspond to the UIDocumentInteractionControllerDelegate protocol and implement the documentInteractionControllerViewControllerForPreview: method and return the presenting controller for the document interaction controller.

class ReaderViewController: UIViewController, UIDocumentInteractionControllerDelegate
    func loadDocUsingDocInteractionController() {

        if let fileURL = NSBundle.mainBundle().pathForResource("SamplePDF", ofType: "pdf") { // Use if let to unwrap to fileURL variable if file exists
            let docInteractionController = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: fileURL)!)
            docInteractionController.delegate = self
    // Return the view controller from which the UIDocumentInteractionController will present itself.
    func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
        return self

The UIDocumentInteractionController has the below methods for various cases:

  • presentPreviewAnimated: for presenting the preview controller.
  • dismissPreviewAnimated: to programatically dismiss the preview.
  • presentOptionsMenuFromBarButtonItem:animated: to provide an action sheet with options to share/print etc.
  • presentOpenInMenuFromBarButtonItem:animated: to provide an action sheet with options to open the file in a different application which supports the document type.

4. Alternate PDF viewers

There are few commercial libraries also available but one of the best third party libraries remain to be the VFR Reader. Also it is free and open source🙂

You can check the project here:

That’s all there is to it. Thanks for reading!🙂


  1. Apple: UIWebView Class Reference
  2. Apple: QLPreviewController Class Reference
  3. Apple: UIDocumentInteractionController Class Reference
  4. Apple: PDF Document Creation, Viewing, and Transforming

Localizing Storyboards and XIB’s

Further to the previous post on Internationalization and Localization in iOS, this comment by a kind reader prompted me to do a detailed write up on Localizing Interface Files in Xcode.

Localizing Storyboards and XIB’s

Pre-Requisite: Enabling project for Localization

In order to provide translations to different languages, we should enable Localization in the project as a pre-requisite. Which is done as shown below. (Note: Your project may already have it enabled)

Xcode Project: Project -> Info -> Select Use Base Internationalization
Xcode Project: Project -> Info -> Localizations: Select “+” and choose the languages you want to support.

Once you add a language, you will be prompted to select the files to localize, such as the Main.storyboad or LaunchScreen.xib.

(Screenshots available here: Internationalization and Localization in iOS)

Localizing Storyboards

Step 1: Enable Localization
While enabling the project to be localized in the Pre-Requisite, we had localized the Main.Storyboard and the LaunchScreen.xib files as well.

In case you have added a new storyboard or xib file, you can localize it by:
Select Storyboard/xib file -> Inspector -> localize.

You can then select the languages that you want to localize your file for.


You can localize interface files in two ways:

  1. Using separate storyboard/xib files for different locales.
  2. Using strings file for different languages and by providing translated text.


Since, using separate storyboards/xib’s will be an overhead both in terms of maintainability and upgradability along with increasing the application’s bundle size for large projects, you should no do that unless absolutely necessary. Such as in cases where you want to provide a slightly different layout for a particular localization say a Right-to-Left language for instance.

So, the following steps describe how to localize the storyboard/xib’s using localizable strings file.

Step 2: Providing Translations
Every UI element in the storyboard has a unique identifier known as Object ID. Which can be seen in the inspector panel on selecting any UI element.

Translations are provided for each of the elements using their Object Id’s. The automatically generated strings file contains key value pairs. The keys represent the label displayed in the UI and the values correspond to the display strings.

Providing a French translation to name, for instance is just as simple as updating the value for the corresponding label text in the Main.strings (French) file.

/* Class = "UILabel"; text = "Name:"; ObjectID = "gCq-Ww-rgP"; */
"gCq-Ww-rgP.text" = “Nom:";


Translations can be applied to any number of locales/languages in a similar way.

Step 3: Testing the changes
Translations can be tested by:

  1. Changing the device/simulator language in settings and re-running the application.
  2. Using Preview option in the Assistant Editor and setting the locale (screenshot below).

(You can also verify the frames of UI Elements using pseudo-language selection in preview for pseudo-localization.)SBL_PreviewLocalization.png

If you are not familiar how to preview the storyboard:

Opening Preview Pane
Opening Preview Pane

All set now. Ready to build and deploy?🙂

The App Update Cycle

So that was my app’s version 1.0.

Now I am updating my application to version 2.0 with a load of amazing features and in the process have added few more screens to my storyboard and few new items to the xib’s.

How do I then provide localization to the new items?

Step 4: Updating localization for updated UI items

In our case, we already have localized our interface files. But now that we have updated them, we need to localize the new UI elements. This can be done in three ways. (of course there are many other ways. But we will look at the below three. In fact only one. Jump to method 3 if you quickly want to do with it! ;) )

Method 1: Full Manual

One way is to copy the identifier of the UI Item (ie., the Object ID), provide transitions and manually add it to the existing strings file. Do add necessary comments so you don’t get confused later on.😉

That sounds like a real PITA.
Ok. Moving on.

Method 2: Using ibtool

Another way is to update the strings file as described by Apple here:

This involves the following three steps:

  1. Generating new strings file.
  2. Comparing and merging the changes. MANUALLY.
  3. Providing translations for new strings.

Most probably, you will dump this method because of the second step. Isn’t that right?😉

Method 3: Using AppleGlot

So there is one another way you can automate the merging part.
Did I hear that right?
Yeah! thanks to the AppleGlot.

You can download it from below: <Requires Login>
Apple: Downloads for Apple Developers: Search AppleGlot

It also comes with a pdf manual “AppleGlot 4 User’s Guide”

Updating the storyboard/xib strings file.

* NOTE: Perform the below steps only on a copy of your application so that you always have the original un-modified version in case you need to revert back any changes. *

Before we go further, AppleGlot requires few things to function properly. Which being an Old Codebase (AppleGlot folder: _OldBase), a Localized Old Codebase (AppleGlot folder: _OldLoc) and a New Codebase (AppleGlot folder: _NewBase) of the application. Read the AppleGlot User’s Guide for description on the following steps and other information.

# For our purpose, in the above scenario, we will call the current codebase (which has new storyboard items and a strings file which doesn’t contain those new items.) as the _OldBase and _OldLoc.

Step 1: Download and Install AppleGlot.
Step 2: Create a folder to work with and give it a name say “AppleGlot_env”.
Step 3: Open Terminal and navigate to the newly created folder. (Provide your path or drag-drop the folder to terminal next after entering $  cd)

$ cd path/to/AppleGlot_env

Step 4: Run the below command. This generates folder structures to work with.

$ appleglot create
AppleGlot Folder Structure
AppleGlot Folder Structure

Step 5: Copy the current application to the folders _OldBase, _OldLoc and _NewBase (For our case.)
Step 6: Open the application project in the _NewBase folder.
Step 7: Open the Main.storyboard file, select File Inspector and un-select the localised language.
(Select Remove in the Alert that is prompted. You may also choose to pick the option to “Delete localised resource files from disk”)

SBL_Alert1.png Step 8: Now select the localization languages to generate a new strings file and save the project.
(If you are prompted with an alert titled File Already Exists, choose the Replace File option.)

SBL_Alert2.png Step 9: Run the command appleglot setlangs base_lang target_lang in terminal to set the base and target languages. For our example considering English as the base and French as the target language.

$ appleglot setlangs en fr

Step 10: Run the populate command which cross-references the provided codebases and generates the merged files in the _NewLoc folder.

And. Thats it! You can find the new project with all the newly added strings which also retains your previous translaions in the _NewLoc folder🙂

Pending: Updating translations to the new strings.
You can add the translations to the new strings manually inside the strings file.

Another advantage of using AppleGlot is that above command appleglot populate generates a XLIFF file in the _Translations folder which you can share with translators and later on import it into the project.

  1. Using Xcode: After choosing the Project Target,
    Editor -> Import Localizations.SBL_ImportLoc.png
  2. Using AppleGlot:
    Follow steps 6, 7 and 8 in the AppleGlot User’ guide document.
    Some tools for adding translations to XLIFF files are provided here:
    GitHubGist: maremmle user

Note: The online tool Brightec: Online XLIFF Editor seems to do the job but on importing the file to Xcode I had no luck in updating the translations.😦 (maybe the generated format was different, maybe I did something wrong! Will update you once I find a solution that works.)

Thanks for reading!


  1. Apple: Internationalization and Localization Guide: Localizing Your App
    Also read topics on Exporting Localizations and Importing Localizations from translators in the above link.

Other methods for working with localization of interface files:

  1. Ole Begemann: Automating Strings Extraction From Storyboards for Localization
  2. StackOverflow: Is it possible to update a localized storyboard’s strings?

Auto Layouts in iOS

* This tutorial uses Xcode 6 and iOS 8 *

Auto Layouts today are inevitable for any application. Be it an iPhone or an iPad application. That is because the device sizes are ever changing and also because of new iOS features like multi tasking for iPad makes the available screen size for your application dynamic. To take advantage of all these things, we will have to use Auto Layouts in our applications. In other words, don’t go away unless you finish reading this if it is new to you🙂

What is Auto Layout?

Auto Layout is a system that lets you lay out your app’s user interface by creating a mathematical description of the relationships between the elements. You define these relationships in terms of constraints either on individual elements, or between sets of elements. Using Auto Layout, you can create a dynamic and versatile interface that responds appropriately to changes in screen size, device orientation, and localization.

– Apple: Auto Layout Guide

Auto Layout Terminology

What are Constraints?

Constraints are basically rules that specify how different views should be positioned while using Auto Layouts.

The fundamental building block in Auto Layout is the constraint. Constraints express rules for the layout of elements in your interface; for example, you can create a constraint that specifies an element’s width, or its horizontal distance from another element. You add and remove constraints, or change the properties of constraints, to affect the layout of your interface.

When calculating the runtime positions of elements in a user interface, the Auto Layout system considers all constraints at the same time, and sets positions in such a way that best satisfies all of the constraints.

– Apple: Auto Layout Concepts

Settings Constraints to views:
  1. Apple: Working with Constraints in Interface Builder
  2. Apple: Working with Auto Layout Programmatically

Settings constraints programmatically uses Strings in the Visual Format Language: Apple: Visual Format Language

The constraints are installed on generic or specific size classes.

Setting Constraints in Interface Builder

What are Size Classes?

Size Classes are a feature that allows you to layout views for various screen sizes generalised as a Size Class. Size Classes are either Regular or Compact. Whenever any constraint is defined for Auto Layouts, we can specify them for any particular Size Class or generalise for all the Size Classes. iOS uses the below size classes for Auto Layouts and allows us to choose out of the below options while working on storyboards and while setting constraints for the views.

Size Classes
Different Size Classes

Read more about Size Classes here:

Frame and Bounds and Centre Properties

Bounds: Bounds contain the view’s width and height properties.

Frame: Frame corresponds to the position of a view within it’s superview. It has x, y co-ordinates as well as width-height of the view. (This would be different than the view’s bounds if the view is rotated or some transformation is applied to the view.)

Centre: The views centre is the central point in the view within the superview.

Not clear? Follow the below links.

What is Intrinsic Content Size?

Defining an Intrinsic Content Size helps avoiding ambiguity during design time. System items such as UILabels adjust width automatically and hence doesn’t require Intrinsic Content Size to be defined. While for Custom views you can override the function intrinsicContentSize to return the correct size during runtime.

Frame Rectangle and Alignment Rectangle

Auto Layout operates on the so called Alignment Rect. The alignment rect considers the required portion of the view like Label in a Button and excludes any ornamentation like Shadows.

I am not getting this:

Auto Layouts and Auto Resizing Masks

In case you have been working Auto Resizing Masks before using Auto Layouts, you can use the below guide to adopt Auto Layouts. Auto Resizing masks can be easily translated into constraints by setting the property translatesAutoresizingMaskIntoConstraints to YES.

Adopting Auto Layouts in your Application

Pre-Requisites: Enabling Auto Layouts

For this demo I am choosing the Single View application from Xcode templates and creating a Universal Application so that it can be tested for both iPhone as well as iPad devices.

Once we an application to work with, enable Auto Layouts by:
Select Main.storyboard -> Utilities bar -> File Inspector -> under Interface Builder Document section: Select Use Auto Layout and Use Size Classes.

Enabling Auto Layouts and Size Classes
Enabling Auto Layouts and Size Classes

1. Installing Constraints

For this example, Let us assume we have two views one on top of another. You can set different background colour to the views to make it easy to see Auto Layouts in action!

a) Adding Constraints In Interface Builder
Interface builder allows you to add constraints to the views in multiple ways. There are interactive ways such as control dragging from a view to a parent or adjacent view to set constraints between the two views.

Once the storyboard is opened, the bottom toolbar of the editor will have three buttons on the right end “Align”, “Pin” and “Resolve Auto Layout Issues”.

In this example, the view controller has two views that looks like the screenshot below. Lets call the two views A and B. (To add a view to the view controller, Open the “Utilities” bar (Top Right End button), Open the “Object Library” search for a View and drag and drop on the storyboard. Resize and adjust frame manually or by using the Size Inspector. Change colour by selecting the view and using the Attributes Inspector.)

Adding Individual Constraints:

  1. Select view A.
  2. Click on Pin button at the bottom right of the editor.
  3. Unselect “Constrain to Margins”.
    (This is because the superview will have some inherent margins which we don’t care for now.).
  4. Set the values for spacing to 10 on all four sides and select the spacing lines (the dotted lines will turn solid).
  5. Repeat steps 2-4 for view B.
  6. Preview the effects (See section 3 below).
Adding Constraints

You will notice that the view B is not seen in the preview. This is because we have not set an proper relation between views A and B and also if you notice the red warning in the Document Outline, it tells that some constraints are missing which means that we are not providing enough constraints for the iOS to layout the views. To resolve the issues we can ask Xcode to resolve issues for us as described below (See section 4 below).

Previewing after Setting Constraints

For this example, let’s see you need the two views A and B to have equal heights, you can add “Equal Heights” constraints to resolve this issue.

Adding Equal Heights Constraints:

  1. Select views A and B.
  2. Click on Pin button at the bottom right of the editor.
  3. Select “Equal Heights”.

Now, if you observe, the layout issues have been resolved and you can preview that the views A and B now have equal heights.

Previewing after Adding Equal Heights Constraints

b) Adding Constraints Programatically

You can also programatically set the constraints. This is described in the below Apple guide.

3. Previewing the changes

Xcode provides a very useful tool to inspect your layout in various devices without actually having to run the application! Yes🙂

Opening Preview Pane

4. Resolving Auto Layout Issues

Interface Builder shows ambiguity such as unfulfilled or missing constraints by providing warnings and by adding orange borders around frames. The below document explains how to resolve such issues in various cases.

Where to go from here?

Going through the below references and trying out examples for couple scenarios would be the next best thing to do. Auto Layouts are convenient. But if you do not understand how they work or even if you don’t know what are the different features available for Auto Layouts, it can turn to be a real PITA in some scenarios.

Other Interesting Things

  1. Content Hugging Priority and Content Compression Resistance
    1. StackOverflow: Cocoa Autolayout: content hugging vs content compression resistance priority
    2. Ray Wenderlich Forum: Ch 3. Beginning Auto Layout Content Hugging Explanation???
  2. Multiplier, Constant and Priority field
    1. Apple: Editing Auto Layout Constraints
  3. Stretchable Views: This is not completely related to Auto Layout but also not completely different if you need stretchable views. Hence its here🙂
    1. Apple: View Architecture Fundamentals: Stretchable Views


  1. Apple: Auto Layout Guide
  2. Apple: Auto Layout By Example

Developer Videos

  1. Apple: WWDC 2015: Mysteries of Auto Layout, Part 1
  2. Apple: WWDC 2015: Mysteries of Auto Layout, Part 2


  1. Ray Wenderlich: Auto Layout Tutorial Part 1: Getting Started
  2. Ray Wenderlich: Auto Layout Tutorial Part 2: Constraints

Further Reads

  1. ObjC.IO: Advanced Auto Layout Toolbox
  2. Big Nerd Ranch: iOS Auto Layout: Fun Facts and Tips

Text Kit and Dynamic Type in iOS

* This tutorial uses Swift *

What is Dynamic Type and why should I care?

Dynamic Type refers to dynamically adjusting the font family, font size when the user requests a bigger/smaller/bolder font in iOS Accessibility settings for his/her reading comfort.

Adopting Dynamic Type in your application enables iOS to enhance the legibility of texts thus making it convenient for users to read text in your application.

So lets start over🙂

Implementing Dynamic Text in your application:

1. What is already available and what is not

If you are using UITableView in your application with standard cells, you might be surprised if I tell you that they already use Dynamic Type for title and sub titles. To verify this, follow the below steps. (If you don’t have a project already to test, you may download a sample reminder application called iRemind.)

This application has below two screens as under normal settings.

DynamicText_2.1 DynamicText_2.2

Testing: Changing text size for accessibility in iOS 8

Open the Settings app and navigate to General -> Accessibility -> Larger Text. Enable “Larger Accessibility Sizes” and use the slider to increase/decrease the sizes.

Normal Setting
Larger Font

You can now re-run the application to check which all components already adopt to the performed changes.

2. Using Dynamic Type for Common UI Elements

To make use of Dynamic Types, we need to specify a Font Style instead of Font Name and Size which allows iOS to select the appropriate Font Sizes/Types based on the user’s preference. For UI elements such as UILabel, UITextField, UITextView and so on, using dynamic Type is as simple as it can be.

Using Storyboards/XIB’s:

If you are using Storyboards or XIB’s, we can set it in the Attributes Inspector as shown below:

  • Select the UILabel (for example)
  • Select the Attributes Inspector button from the Utilities pane
  • Select the font and set it to one of the given Text Styles


On selection of these Text Styles, you will notice that you are no more allowed to select the Font Family or Size. Which is because these are automatically adjusted based on the user’s preferences.

Programatically Setting the Fonts:

For setting the values programmatically, set the font of the UILabel (for example) to the one of the predefined values as below.

    override func viewDidLoad() {
        // Adjust font for UI elements
        self.nameTextField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
        self.detailsTextView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
        self.nameLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
        self.detailsLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
        self.timeLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)

UIFont has a function preferredFontForTextStyle() which returns the correct font based on the TextStyle as per the user’s accessibility preference.

Below are the available font styles:

    // Font text styles, semantic descriptions of the intended use for a font returned by +[UIFont preferredFontForTextStyle:]
    // UIFontTextStyleHeadline
    // UIFontTextStyleBody
    // UIFontTextStyleSubheadline
    // UIFontTextStyleFootnote
    // UIFontTextStyleCaption1
    // UIFontTextStyleCaption2

Once the changes are done, run the application after setting a larger text in Settings.

Note: The change will not be reflected if you are just re-launching the application from background to the same screen. This is because, when the UI element is created, it will use the appropriate font as per the settings. But once it is rendered on the screen, it is not clever enough to adjust the font. So re run the application by killing it from background after the settings have been changed.

To fix this issue, we will have to add a handling in our controller to set the correct fonts whenever the settings are changed.

3. Handling text size changes in Accessibility Settings

When the text sizes are changed in Accessibility Settings, we will have to just reset the font for the UI elements. When we reset the font, the new font is returned by the function preferredFontForTextStyle() based on the user preferences. Sample implementation below requires the following steps.

  • Adding the controller/view as observer for for changes in accessibility setting font size which is called by the name UIContentSizeCategoryDidChangeNotification for registering to the notification.
  • Resetting the fonts when the notification is received.
  • If you are using a table view, reloading the table view would also be required. Which in turn would reload the cells and reset the fonts.
    override func viewDidLoad() {
        // Adjust font for UI elements

    override func viewDidAppear(animated: Bool) {
        // Add observer to observe changes in text accessiblity
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "setFontForContentSizeChange:", name: UIContentSizeCategoryDidChangeNotification, object: nil)
    override func viewDidDisappear(animated: Bool) {
        // Remove observer
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)

    func setFontForContentSizeChange(notification: NSNotification?) {
        self.nameTextField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
        self.detailsTextView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
        self.nameLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
        self.detailsLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
        self.timeLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)

Below are the screenshots from the sample application after the changes.

DynamicText_4.1 DynamicText_4.2

Wait. where’s the source code for these changes? Are you not gonna share that? Is that a NO? Well, Seriously?😉

4. Custom implementation to support custom font

It is recommended to use the predefined font styles but in cases where you need to use custom fonts, we can still support dynamic type with the help of the notification that is posted on content size change. Since this is not quite straight forward, one option would be to use the values in the userInfo dictionary of the notification object to change the fonts in the application.

The notification object includes the following details.

    name = UIContentSizeCategoryDidChangeNotification;
    object = <UIApplication: 0x7fb852e12f30>;
    userInfo = {
        UIContentSizeCategoryNewValueKey = UIContentSizeCategoryAccessibilityExtraLarge;
        UIContentSizeCategoryTextLegibilityEnabledKey = 0;

The various available values for content size categories being:

// Constants from UIApplication Class
// Content size category constants
let UIContentSizeCategoryExtraSmall: String
let UIContentSizeCategorySmall: String
let UIContentSizeCategoryMedium: String
let UIContentSizeCategoryLarge: String
let UIContentSizeCategoryExtraLarge: String
let UIContentSizeCategoryExtraExtraLarge: String
let UIContentSizeCategoryExtraExtraExtraLarge: String

// Accessibility sizes
let UIContentSizeCategoryAccessibilityMedium: String
let UIContentSizeCategoryAccessibilityLarge: String
let UIContentSizeCategoryAccessibilityExtraLarge: String
let UIContentSizeCategoryAccessibilityExtraExtraLarge: String
let UIContentSizeCategoryAccessibilityExtraExtraExtraLarge: String

I am gonna leave this implementation to you🙂

5. Adjusting the font size for dynamic text in constrained layouts

For dynamic texts or translations that are difficult to fit in the given frame, you can use the below property and provide a minimum font size/scale  and the OS will automatically scale the text to fit any given width. (And Yes! if the text is too long it will definitely be truncated. ;))

UITextField has the below two properties to specify if you want the text to adjust the font automatically.

    adjustsFontSizeToFitWidth // Set this Bool to true to allow shrinking of text.
    minimumFontSize // Specify the minimum font values here.

For UILabel has the bellow property to set the scale factor. 0.0 being the default value and the current font size being the lowest font size.

    minimumScaleFactor // Set the value as a fraction of the font to be considered the minimum value.

This can also be done in the storyboard as shown below:

  • Select Autoshrink (Default value is preselected as Fixed Font Size).
  • Change it to Minimum Font Scale/Size.
  • Set the value for Scale/Size.
  • Optional: Select Tighten Letter Spacing to squeeze in more text.


This tutorial complements the previous tutorials on Internationalization and Localization in iOS and Accessibility in iOS: VoiceOver. Do check them out!🙂


  1. Apple: Text Programming Guide for iOS
  2. Ray Wenderlich Tutorial: Text Kit Tutorial: Getting Started

Accessibility in iOS: VoiceOver

What is Accessibility?

Accessibility in iOS allows users with hearing disabilities and visual impairments to access iOS and your application by supporting various features like Voice Control, VoiceOver, White on Black, Mono Audio, Speech to Text and so on.

More accessibility features are described in: Understanding Accessibility on iOS by Apple.

Why make use of Accessibility in my Application?

Here are the two main reasons:
One, it will enable more users to access your application and its features. Secondly, it is quite simple to implement.

Apple: Why You Should Make Your App Accessible

How to: Use Accessibility features in iOS – Apple Support

Starting with VoiceOver in iOS

VoiceOver is Apple’s innovative screen-reading technology, which gives users control over their devices without having to see the screen. VoiceOver does this by acting as an intermediary between an application’s user interface and the user’s touch, providing audible descriptions of elements and actions in the application.
– Apple: Accessibility Programming Guide for iOS: Accessibility and VoiceOver

VoiceOver enables users with visual impairments use your application with the help of an audio guide which provides audio clues for using iOS applications.

Supporting VoiceOver in your Application

Enabling VoiceOver in your application is as easy as pie. All you need to do is specify the values for various accessibility attributes such as those below.

Accessibility Properties

isAccessibilityElement: Is a boolean that specifies whether an UI element is visible to assistive technology. In other words if iOS should provide help for this element.

All controls and labels have this set to YES by default.

accessibilityLabel: this is a string that specifies the label of the UI element. This usually would be same as the label that is being displayed in the UI/screen.

accessibilityHint: this is a string that provides descriptive details about the accessibility element.
For instance a button might might have a description of what action is performed on clicking the button.

Below example shows setting accessibility values for a table cell “cell” which has a label called “textLabel”. UIAccessibility is an extension of NSObject and hence can be used on pretty much everything in cocoa.

            let cellTextLabel : UILabel = cell.textLabel!
            cellTextLabel.text = NSLocalizedString("Create New Reminder", comment: "Creates New Remainder")
            cellTextLabel.isAccessibilityElement = true
            cellTextLabel.accessibilityLabel = NSLocalizedString("Create New Reminder", comment: "Creates New Remainder")
            cellTextLabel.accessibilityHint = NSLocalizedString("Select to create a New Reminder", comment: "Create New Reminder accessibility hint")

If you are not familiar with NSLocalizedString, do check out Internationalization and Localization in iOS.

accessibilityTraits: For custom UI in the application, we can also specify what is called as accessibilityTraits.
These will help describe the various functions of the UI element.

It has values like:
and so on.

Apple: UIAccessibility Protocol Reference: Accessibility Traits

In case you have added a custom item that also behaves as a button, add the button trait as below.

view.accessibilityTraits = (view.accessibilityTraits | UIAccessibilityTraitButton)

Note: UIAccessibilityTraits is a mask that combines all accessibility traits and hence, always add the new Accessibility trait to the existing list.

accessibilityValue: For UI elements that change their values like a UIPicker or a UISlider, you can set the current value to the accessibilityValue property whenever it gets updated so that it will be spoken by the VoiceOver.

UIAccessibilityAction Protocol: For complex actions associated with accessibility elements, there is a UIAccessibilityAction protocol which defines few methods for handling such scenarios when user double taps to select the action.
More information on this here:

Apple: UIAccessibilityAction Protocol Reference

UIAccessibilityContainer: These are essentially used when a single view contains multiple accessibility elements Or even when a view has small text elements or badges that are hard to individually select to have their own accessibility values.

Required for elements that aren’t views. For instance elements like drawing on a view.

It has a property accessibilityElements which is an Array which also means it is an ordered list. Hence, it can be used to contain multiple accessibility elements and VoiceOver will go over the elements in the same order as the elements in this list.

(This is helpful in cases where reading the labels in the order of their appearance is confusing or sometimes even incorrect.)

Lets suppose you have a view/cell as below:

Brian O’Connor
Male                              Born
26                                   25/Dec/1988

The default sequence would read out in the below order.

Brian O’Connor

Which of course doesn’t make sense for someone with visual impairment and can be corrected by adding the elements in the required order to the accessibilityElements property.

Brian O’Connor

UIAccessibilityCustomAction: Custom actions allows users to provide custom actions to be performed on accessible objects. More details on this here.

Apple: UIAccessibilityCustomAction Class Reference

Testing the Application for VoiceOver

1. On an iOS device: Using VoiceOver from settings.

On Device: Settings > General > Accessibility > VoiceOver: ON

Note that, once VoiceOver is ON, single tap does not open the application. Instead single tap highlights an accessibility element and reads over the accessibility label and hints on the element. You will have to double tap to select the item and double tapping can be done anywhere on the screen to select the highlighted item.

For more details on this refer to the guide below:
Apple: Test Accessibility on Your Device with VoiceOver

2. On iOS Simulator: Using Accessibility Inspector.

On Simulator: Settings > General > Accessibility > Accessibility Inspector: ON


Sample screenshot of above implementation:


The accessibility inspector on the simulator is displayed in a dialog as shown below and there are no audio clues as on an actual device. Hence, the application needs to be tested on a device to verify if is working as expected prior to shipping.


  1. Apple: Accessibility on iOS
  2. Apple: Accessibility Programming Guide for iOS
  3. Apple: Debug Accessibility in iOS Simulator with the Accessibility Inspector
  4. Use Your Loaf: VoiceOver Accessibility (Objective C tutorial)