Swift – UITableViewRowActions and editActionsForRowAtIndexPath

Do you like those button that display when you swipe a row in a table view to the left? You can add your own with little effort using UITableViewRowAction, and tableView(:editActionsForRowAtIndexPath).

tableView editActionsForRowAtIndexPath is a UITableViewDelegate method. This method returns an array of UITableViewRowAction’s. Each of these row actions includes a style, title, and action. The action receives the index path of the row where the action was executed.

Here is a sample gist:


Swift – Singletons

Singleton and the TodoManager

The goal of the current project is to create a Todo App. This app will work with Todo items that need to be shared across more than one view controller. One approach is to create a single instance of a class that can be shared across the entire app. This is called a Singleton.

What is an instance?

A class file describes a type of object that can be created from that class. Each Object created from a class is called an Instance. For example our app will store Todo items. These are defined in the Todo class.

class Todo {


A class will define the properties, and methods of an object, and include an initializer.

class Todo {
var name: String
var completed = false
init(name: String) {
self.name = name

Create an instance of a class by using the name of the class like this.

var somethingTodo = Todo(name: “Eat Breakfast”)

In this case somethingTodo is an object with properties of name, and completed.

Each time you use Todo(name: “”) you are creating a new instance of Todo. Each instance stores it’s own unique values for name and completed.

This method works well for Todo items since we want to create a new and unique entry each time we create a Todo.

If our app contains a list of todos, we need to make these available across multiple View Controllers. If the Todos are stored in an array that belongs to (is a property of) One View Controller it’s very awkward to make todos available to other view controllers.

A better approach is to create a separate class to manage the list of todos. This class will be responsible for holding the list of Todos, relaying the count of todos, adding new todos, deleting todos, etc.

Keeping all of the code that manages Todos in one class helps keep our code organized. All of the methods and properties that manage our list of todo items will be in one place. Imagine the TodoManage class looks something like this:

class TodoManager {
var todos = [Todo]()
var count: Int {
get {
return todos.count
func addNewTodo(name: String) {

func getTodoAtIndex(index: Int) -> Todo {


There is one problem. Imagine we have three view controllers:


Now imagine that each of these creates a new instance of TodoManager:

Here each view controller has it’s own instance of a TodoManager. That’s three unique managers. This won’t work for our app. Imagine that the app adds a new Todo to the manager owned by AddNewTodoManager. The todos array in List, and Details would not be updated to match.

What we need to create is something that looks like this:

Imagine in this arrangement that each ViewController has a manager property that points to the same instance. Now List View controller is displaying the same list of todos that Add new and details are working with.

Really what we will create is something that will look more like this:

Imagine here that TodoManager owns an instance of itself, and other classes can access that instance.

Singletons and Shared instance
Singleton is the name of a software design pattern. A design pattern is a standard solution for common programming problems. Our todo app is trying to solve a standard software problem: we need single instance of a class that can be shared.

Static/Class properties
Normally classes will only use instance properties. In the case of the Todo class, name and completed are instance properties. Instance properties belong to each instance, and each instance stores it’s own unique values for these properties.

Classes can also define static properties. These properties belong to the class, not to each instance! here’s an example class:

class Test {
static var name = “Hello World”
var number = 10

The first property is static, and belongs to the class, while the second property is an instance property, which each instance will have.

Test.name // “Hello World”
var instanceOfTest = Test()
instanceOfTest.number // 10

Working with a singleton
The singleton pattern works like this, we’ll use the TodoManager as an example. This class wants to manager a list of Todos that it can share with other classes in our app.

The TodoManager class starts like this:

class TodoManager {
static let sharedInstance = TodoManager()

private init() {


Notice the property sharedInstance is static. This makes it a class property. You’ll access it with:


This property is also a constant, let. This means it can only have one value. You can’t set change its value once set.

To complete the pattern we mark the initializer: init() with private. This means that this method is only accessible within this class. You won’t be able to access the initializer from outside of the class.


Swift – NSNumberFormatter

At some point you will find yourself in need of formatting numbers. This could be for time, temperature, currency, or just wanting to control the number of decimal places. You might even want to convert numerals to words. The NSNumberFormatter does all of this.

Figure this is a very common task so, someone will have made a library of code to handle it. The Cocoa Touch framework provides the end all in number formatting  in NSNumberFormatter.

Using the NSNumberFormatter is easy though, maybe, not intuitive until you work with it a few times.

The steps are easy:

  1. Make an instance of the NSNumberFormatter.
  2. Set options…
  3. Call the formatter.stringFromNumber() method.

A use case might look like this:



The example above creates a number formatter that converts a value into a currency style. NSNumberFormatter, in this case, should convert “cost” into currency formatted number for the current locale.

This is very sophisticated, and powerful, for very little work on our part.

The second step is where things get hazy. There are many options you can choose from. We can break these down into styles, and options.

You can think of styles as predetermined, standardized ways of expressing numbers, and options as the details that might make up a style.

For example a style might be currency style. This might include options for rounding to two decimal places, and adding a comma every third significant digit, while preceding everything with the correct currency symbol.

Options on the other hand, would things like setting the number of digits before the decimal point, and the number of digits after the decimal point. Setting the character used for the separator, like the “.”, or “,”.

Here are a few examples:


Swift – Simple Animations

Need to create simple animation? Use UIView.animateWithDuration() or one of the other similar methods. While this is fairly easy to use, it is bit cumbersome. Why not make a helper method to simplify your work?

  1. Imagine a method that takes a UIView as a an argument. Since all UI elements are sub classes of UIView you can pass any UI element.
  2. For convenience imagine all of the elements were created at the location where they will end their motion. This means our method will offset the element in the x and or y, then move it back to it’s starting point.
  3. To make the motion interesting and give us some controller we need to pass in the duration.
  4. If everything is moving at the same time things are dull, and some things are not possible. We need a delay.

Our method looks like this:

func animateThing(thing: UIView, offsetY: CGFloat, offsetX: CGFloat, time: NSTimeInterval, delay: NSTimeInterval) {
// some code here 

The parameters are

  • thing – a UIView or subclass of UIView, which is the thing to animate
  • offsetY – CGFloat the amount to offset in the y axis. This sets the starting point on the y axis, thing will move back to original position!
  • offsetX – CGFloat the amount to offset on the x axis.
  • time – NSTimeInterval, this can be a Double (0.5 for example), it sets the length of the animation in seconds
  • delay – NSTimeInterval, this sets the time to wait before beginning the motion.

A few points

  1. The offsetX, and offsetY can use positive or negative numbers. Negative values move the object left or up. Positive numbers move down, or right. These determine an offset, that places the object at a new position before the motion begins, the object will end its motion at it’s starting point.
  2. Time is set in seconds. Delay determines how long to wait before the motion begins. The total time of the animation will be time + delay.
  3. It’s probably best to call this function in viewWillAppear. This way the objects get positioned before we see the view, and the motion will be applied each time the view is shown.

Using an Extension

An extension allows you to add functions to existing classes. Rather than adding this function to each custom view controller we create, using an extension we can add an extension to the UIViewController class, and all ViewControllers will have the new function.

Add the first code example to your project in a file named extensions.swift. You’re done! The second code example shows some usage examples and is not required.

Swift – Camera and UIImagePickerController

Take pictures with the UIImagePickerController. This is a ViewController subclass, that creates a view that allows you to take a picture with the camera.

The UIImagePickerController works with a Delegate to handle working with an image after it has been taken.

Try it for yourself. Create a ViewController with a UIImageView, add an IBOutlet for this. We will use this to display the image, so we need a reference.

Add a UIButton, and add an IBAction. Use this to open the Image Picker controller.

In the button action add:


Parse Swift with Cocoapods

  1. Xcode new project
  2. Terminal CD to project directory
  3. Open your Podfile with: open -a Xcode Podfile
  4. Uncomment Frameworks, and add Parse, and ParseUI to do. Should look something like this:
  5. # Uncomment this line to define a global platform for your project
    # platform :ios, '8.0'
    # Uncomment this line if you're using Swift
    target 'SpringShowApp' do
    pod 'Parse'
    pod 'ParseUI'
  6. Quit Xcode
  7. In terminal: pod install
  8. When Terminal is finished, open your project from the ProjectName.xcworkspace. From this point on, you will need to open the project from this file!

Swift – Open an Alert box

Opening an alert in iOS is very easy. Use the UIAlertController. This creates a special ViewController that can be displayed in one of two styles Alert, or ActionSheet.


let alert = UIAlertController(title: "Send Cypher", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let message = UIAlertAction(title: "Message", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
    // Do something when message is tapped

let email = UIAlertAction(title: "Email", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
    // Do something when email is tapped

let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)

presentViewController(alert, animated: true, completion: nil)

Swift – Send Email

Sending email with Swift is easy with MFMailComposeViewController. Follow these steps: 

Step 1: Import the MessageUI framework

import MessageUI

Step 2: Add the Protocol to your ViewController


Step 3: Add the delegate method

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    controller.dismissViewControllerAnimated(true, completion: nil)


Step 4: Make an instance of the MailComposeViewController, and present it.

func sendEmail() {
    let mailVC = MFMailComposeViewController()
    mailVC.mailComposeDelegate = self
    mailVC.setSubject("Message Subject")
    mailVC.setMessageBody("Message text...", isHTML: true)
    presentViewController(mailVC, animated: true, completion: nil)





Swift – Send SMS Messages

Sending SMS messages in Swift is very easy. You can add the capability to any app with a few lines of code.

Note: This will not work in the simulator, as the simulator doesn’t support SMS messages!

Step 1: Import MessageIU

Add the following to the top of your ViewController.

import MessageUI

Step 2: Add the Protocol

Add the MFMessageComposeViewControllerDelegate your ViewController definition. 

Step 3: Conform to the protocol

Conform to the MFMessageComposeControllerDelegate by adding defining the:

messageComposeViewController:didFinishWithResult method. It might look something like:

func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
    switch result.rawValue {
    case MessageComposeResultCancelled.rawValue :
        print("message canceled")
    case MessageComposeResultFailed.rawValue :
        print("message failed")
    case MessageComposeResultSent.rawValue :
        print("message sent")
    controller.dismissViewControllerAnimated(true, completion: nil)

You can omit the switch statement. The switch statement provides some feedback to you on the status of the message. Use this to notify your user when a message fails, or is canceled. Or omit if this is unimportant.

Step 3: Open the Message View controller

func sendMessage() {
    let messageVC = MFMessageComposeViewController()
    messageVC.body = "Message string"
    messageVC.recipients = [] // Optionally add some tel numbers
    messageVC.messageComposeDelegate = self
    // Open the SMS View controller
    presentViewController(messageVC, animated: true, completion: nil)